﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.Entity.TD;
using Coldairarrow.Entity.View;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.TD
{
    public partial class TD_CheckBusiness : BaseBusiness<TD_Check>, ITD_CheckBusiness, ITransientDependency, ICheckOperation
    {
        readonly IOperator _operator;
        readonly IOperatorDept _opdept;

        public TD_CheckBusiness(IDbAccessor db, IServiceProvider svcProvider, IOperator @operator, IOperatorDept @opdept)
            : base(db)
        {
            _ServiceProvider = svcProvider;
            _operator = @operator;
            _opdept = @opdept;
        }

        readonly IServiceProvider _ServiceProvider;

        #region 外部接口

        public async Task<PageResult<TD_CheckListDTO>> GetDataListAsync(PageInput<CheckConditionDTO> input)
        {
            var where = LinqHelper.True<TD_CheckListDTO>();
            var search = input.Search;
            Expression<Func<TD_Check, Base_User, Base_User, Base_Department, TD_CheckListDTO>> select = (a, b, c, d) => new TD_CheckListDTO
            {
                AuditUserName = c.RealName,
                ConfirmUserName = b.RealName,
                StorName = d.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<TD_Check>().AsExpandable()
                    join b in Db.GetIQueryable<Base_User>() on a.ConfirmUserId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_User>() on a.AuditUserId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_Department>() on a.StorId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<TD_CheckListDTO, bool>(
                    ParsingConfig.Default, false, $@"Id.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            if (!search.Type.IsNullOrEmpty())
            {
                where = where.And(x => x.Type == search.Type);
            }
            if (!search.CheckTime.IsNullOrEmpty())
            {
                where = where.And(x => x.CheckTime == Convert.ToDateTime(search.CheckTime));
            }
            if (!search.Status.IsNullOrEmpty())
            {
                where = where.And(x => x.Status == search.Status);
            }
            if (!search.IsComplete.IsNullOrEmpty())
            {
                where = where.And(x => x.IsComplete == search.IsComplete);
            }
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<TD_Check> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataAddLog(UserLogType.盘点管理, "Code", "盘点单")]
        public async Task AddDataAsync(TD_Check data)
        {
            await InsertAsync(data);
        }

        [DataEditLog(UserLogType.盘点管理, "Code", "盘点单")]
        public async Task UpdateDataAsync(TD_Check data)
        {
            await UpdateAsync(data);
        }

        [DataDeleteLog(UserLogType.盘点管理, "Code", "盘点单")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        /// <summary>
        /// 获取登录人所属公司的所有仓库
        /// </summary>
        /// <returns></returns>
        public async Task<List<Base_Department>> GetDeptListAsync()
        {
            List<string> deptlist = await _opdept.GetStorString();
            List<Base_Department> listdata = await Db.GetIQueryable<Base_Department>().Where(x => deptlist.Contains(x.Id)).OrderBy(x => x.Sort).ToListAsync();
            if (listdata.Count > 0)
            {
                return listdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        /// <summary>
        /// 递归查找公司下所有的仓库
        /// </summary>
        /// <param name="deptId">组织Id</param>
        /// <param name="deptlist">是仓库的集合</param>
        /// <param name="Departmentdata">组织数据</param>
        /// <returns></returns>
        private List<string> GetDeptItem(string deptId, List<string> deptlist, List<Base_Department> Departmentdata)
        {
            var dlist = Departmentdata.Where(x => x.ParentId == deptId).ToList();
            foreach (var item in dlist)
            {
                if (item.Type == 2)
                {
                    deptlist.Add(item.Id);
                    GetDeptItem(item.Id, deptlist, Departmentdata);
                }
            }
            return deptlist;
        }

        /// <summary>
        /// 获取仓库下的货区信息
        /// </summary>
        /// <param name="storId">仓库Id</param>
        /// <returns></returns>
        public async Task<List<PB_StorArea>> GetStorAreaListAsync(string storId)
        {
            List<PB_StorArea> listdata = await Db.GetIQueryable<PB_StorArea>().Where(x => x.StorId == storId).ToListAsync();
            return listdata;
        }

        /// <summary>
        /// 获取货区下的货架信息
        /// </summary>
        /// <param name="StorAreaId">货区Id</param>
        /// <returns></returns>
        public async Task<List<PB_Rack>> GetStorRackListAsync(string StorAreaId)
        {
            List<PB_Rack> listdata = await Db.GetIQueryable<PB_Rack>().Where(x => x.AreaId == StorAreaId).ToListAsync();
            return listdata;
        }

        /// <summary>
        /// 获取货架下的货位信息
        /// </summary>
        /// <param name="StorRackId">货架Id</param>
        /// <returns></returns>
        public async Task<List<PB_Location>> GetStorLocaListAsync(string StorRackId)
        {
            List<PB_Location> listdata = await Db.GetIQueryable<PB_Location>().Where(x => x.RackId == StorRackId).ToListAsync();
            return listdata;
        }

        /// <summary>
        /// 盘点选择物料信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<TD_CheckLocalMaterialDTO>> GetCheckLocalMaterialAsync(PageInput<MaterialConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<IT_LocalMaterial, PB_Material, Base_Department, TD_CheckLocalMaterialDTO>> select = (a, b, c) => new TD_CheckLocalMaterialDTO
            {
                StorId = a.StorId,
                LocaId = a.LocalId,
                Id = a.MaterialId,
                Name = b.Name,
                Code = b.Code,
                SimpleName = b.SimpleName,
                Spec = b.Spec,
                MaterialTypeId = b.MaterialTypeId,
                RowId = a.Id + "_" + a.MaterialId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<IT_LocalMaterial>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.StorId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            q = q.Distinct<TD_CheckLocalMaterialDTO>();
            var where = LinqHelper.True<TD_CheckLocalMaterialDTO>();
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<TD_CheckLocalMaterialDTO, bool>(
                    ParsingConfig.Default, false, $@"Name.Contains(@0) or Code.Contains(@0) or SimpleName.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            //查询物料类型不为空
            if (!search.MaterialTypeId.IsNullOrEmpty())
            {
                List<string> liststr = new List<string>();
                List<PB_MaterialType> listdata = await Db.GetIQueryable<PB_MaterialType>().ToListAsync();
                var typelist = listdata.Where(x => x.ParentId == search.MaterialTypeId).ToList();
                if (typelist.Count > 0)
                {
                    foreach (var item in typelist)
                    {
                        liststr.Add(item.Id);
                        //递归查询物料类型下的子类型
                        GetMaterialTypeItem(item.Id, liststr, listdata);
                    }
                }
                else
                {
                    liststr.Add(search.MaterialTypeId);
                }
                where = where.And(x => liststr.Contains(x.MaterialTypeId));
            }
            //获取操作者所属工厂下的所有仓库信息
            //List<string> deptlist = await _opdept.GetStorList(_operator.Property.FactoryId);
            where = where.And(x => x.StorId == search.StorId || x.LocaId == search.LocaId);
            return await q.Where(where).OrderBy(x => x.Code).GetPageResultAsync(input);
        }

        /// <summary>
        /// 递归查询物料类型
        /// </summary>
        /// <param name="typeId">物料类型Id</param>
        /// <param name="liststr">物料类型集合</param>
        /// <param name="listdata">物料类型数据</param>
        /// <returns></returns>
        private List<string> GetMaterialTypeItem(string typeId, List<string> liststr, List<PB_MaterialType> listdata)
        {
            var itemlist = listdata.Where(x => x.ParentId == typeId).ToList();
            foreach (var item in itemlist)
            {
                liststr.Add(item.Id);
                GetMaterialTypeItem(item.Id, liststr, listdata);
            }
            return liststr;
        }
        /// <summary>
        /// 检查当前是否有备货单和收货单未完成
        /// </summary>
        /// <returns></returns>
        public async Task<AjaxResult> GetCheckMaterialListAsync()
        {
            //获取工厂下未完成的收货单
            List<TD_Receiving> ReceivingList = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Status < 4).ToListAsync();

            //获取工厂下未完成的备货单
            List<PB_PickUpMain> PickUpMainList = await Db.GetIQueryable<PB_PickUpMain>().Where(x => x.Status < 3).ToListAsync();
            AjaxResult Result = new AjaxResult();
            if (ReceivingList.Count > 0 || PickUpMainList.Count > 0)
            {
                Result.ErrorCode = 1;
                Result.Msg = "收货单或备货单有未完成的";
                //throw new BusException("请把未完成的收货单或备货单完成");
            }
            else
            {
                Result.ErrorCode = 0;
            }
            return Result;
        }


        /// <summary>
        /// 盘点信息保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// 
        [Transactional]
        [DataAddLog(UserLogType.盘点管理, "Code", "盘点单")]
        public async Task AddCheckAsync(TD_CheckDTO data)
        {
            #region
            List<string> deptlist = new List<string>();
            //获取登录人信息
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            string parentId = string.Empty;

            ////获取工厂下未完成的收货单
            //List<TD_Receiving> ReceivingList = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Status < 4).ToListAsync();

            ////获取工厂下未完成的备货单
            //List<PB_PickUpMain> PickUpMainList = await Db.GetIQueryable<PB_PickUpMain>().Where(x => x.Status < 3).ToListAsync();

            //if (ReceivingList.Count > 0 || PickUpMainList.Count > 0)
            //{
            //    throw new BusException("请把未完成的收货单或备货单完成");
            //}

            #endregion
            List<IT_LocalMaterial> listdata = new List<IT_LocalMaterial>();
            List<TD_CheckStor> TD_CheckStorlist = new List<TD_CheckStor>();
            List<TD_CheckArea> TD_CheckArealist = new List<TD_CheckArea>();
            List<TD_CheckRack> TD_CheckRacklist = new List<TD_CheckRack>();
            List<TD_CheckLoca> TD_CheckLocalist = new List<TD_CheckLoca>();
            List<TD_CheckData> TD_CheckDatalist = new List<TD_CheckData>();
            List<TD_CheckMaterial> TD_CheckMateriallist = new List<TD_CheckMaterial>();
            if (data.Type == "1")
            {
                //获取操作者所属工厂下的所有仓库信息
                deptlist = await _opdept.GetStorList(userdata.FactoryId);
                //盘点类型为全盘
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => deptlist.Contains(x.StorId)).ToListAsync();
                foreach (var item in deptlist)
                {
                    TD_CheckStor stordata = new TD_CheckStor();
                    stordata.CheckId = data.Id;
                    stordata.StorId = item;
                    TD_CheckStorlist.Add(stordata);
                }
                await Db.InsertAsync<TD_CheckStor>(TD_CheckStorlist);
                var locallistdata = listdata.GroupBy(x => new { x.LocalId }).Select(x => new { LocalId = x.Key.LocalId }).ToList();
                foreach (var item in locallistdata)
                {
                    TD_CheckLoca locadata = new TD_CheckLoca();
                    locadata.CheckId = data.Id;
                    locadata.StorLocaId = item.LocalId;
                    TD_CheckLocalist.Add(locadata);
                }
                await Db.InsertAsync<TD_CheckLoca>(TD_CheckLocalist);
            }
            else if (data.Type == "2")
            {
                //盘点类型为仓库
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.StorId == data.StorId).ToListAsync();
                TD_CheckStor stordata = new TD_CheckStor();
                stordata.CheckId = data.Id;
                stordata.StorId = data.StorId;
                TD_CheckStorlist.Add(stordata);
                await Db.InsertAsync<TD_CheckStor>(TD_CheckStorlist);
                var locallistdata = listdata.GroupBy(x => new { x.LocalId }).Select(x => new { LocalId = x.Key.LocalId }).ToList();
                foreach (var item in locallistdata)
                {
                    TD_CheckLoca locadata = new TD_CheckLoca();
                    locadata.CheckId = data.Id;
                    locadata.StorLocaId = item.LocalId;
                    TD_CheckLocalist.Add(locadata);
                }
                await Db.InsertAsync<TD_CheckLoca>(TD_CheckLocalist);
            }
            else if (data.Type == "3")
            {
                //盘点类型为物料盘点
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.StorId == data.StorId && data.ListIds.Contains(x.MaterialId)).ToListAsync();
                var materlist = listdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                foreach (var item in materlist)
                {
                    TD_CheckMaterial materdata = new TD_CheckMaterial();
                    materdata.CheckId = data.Id;
                    materdata.MaterialId = item.MaterialId;
                    TD_CheckMateriallist.Add(materdata);
                }
                //添加物料信息
                await Db.InsertAsync<TD_CheckMaterial>(TD_CheckMateriallist);
                //添加仓库信息
                TD_CheckStor stordata = new TD_CheckStor();
                stordata.CheckId = data.Id;
                stordata.StorId = data.StorId;
                TD_CheckStorlist.Add(stordata);
                await Db.InsertAsync<TD_CheckStor>(TD_CheckStorlist);
                var locallistdata = listdata.GroupBy(x => new { x.LocalId }).Select(x => new { LocalId = x.Key.LocalId }).ToList();
                foreach (var item in locallistdata)
                {
                    TD_CheckLoca locadata = new TD_CheckLoca();
                    locadata.CheckId = data.Id;
                    locadata.StorLocaId = item.LocalId;
                    TD_CheckLocalist.Add(locadata);
                }
                await Db.InsertAsync<TD_CheckLoca>(TD_CheckLocalist);
            }
            else if (data.Type == "4")
            {
                //盘点类型库区
                List<PB_Location> Localist = await Db.GetIQueryable<PB_Location>().Where(x => x.AreaId == data.StorAreaId).ToListAsync();
                List<string> locaidis = new List<string>();
                foreach (var item in Localist)
                {
                    locaidis.Add(item.Id);
                    TD_CheckLoca locadata = new TD_CheckLoca();
                    locadata.CheckId = data.Id;
                    locadata.StorLocaId = item.Id;
                    TD_CheckLocalist.Add(locadata);
                }
                await Db.InsertAsync<TD_CheckLoca>(TD_CheckLocalist);

                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.StorId == data.StorId && locaidis.Contains(x.LocalId)).ToListAsync();
                //添加库区信息
                TD_CheckArea areadata = new TD_CheckArea();
                areadata.CherkId = data.Id;
                areadata.StoarAreaId = data.StorAreaId;
                TD_CheckArealist.Add(areadata);
                await Db.InsertAsync<TD_CheckArea>(TD_CheckArealist);
                //添加仓库信息
                TD_CheckStor stordata = new TD_CheckStor();
                stordata.CheckId = data.Id;
                stordata.StorId = data.StorId;
                TD_CheckStorlist.Add(stordata);
                await Db.InsertAsync<TD_CheckStor>(TD_CheckStorlist);
            }
            else if (data.Type == "5")
            {
                //盘点类型货架
                List<PB_Location> Localist = await Db.GetIQueryable<PB_Location>().Where(x => x.AreaId == data.StorAreaId && x.RackId == data.StorRackId).ToListAsync();
                List<string> locaidis = new List<string>();
                foreach (var item in Localist)
                {
                    locaidis.Add(item.Id);
                    TD_CheckLoca locadata = new TD_CheckLoca();
                    locadata.CheckId = data.Id;
                    locadata.StorLocaId = item.Id;
                    TD_CheckLocalist.Add(locadata);
                }
                await Db.InsertAsync<TD_CheckLoca>(TD_CheckLocalist);

                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.StorId == data.StorId && locaidis.Contains(x.LocalId)).ToListAsync();
                //添加货架信息
                TD_CheckRack rackdata = new TD_CheckRack();
                rackdata.CheckId = data.Id;
                rackdata.RackId = data.StorRackId;
                TD_CheckRacklist.Add(rackdata);
                await Db.InsertAsync<TD_CheckRack>(TD_CheckRacklist);
                //添加库区信息
                TD_CheckArea areadata = new TD_CheckArea();
                areadata.CherkId = data.Id;
                areadata.StoarAreaId = data.StorAreaId;
                TD_CheckArealist.Add(areadata);
                await Db.InsertAsync<TD_CheckArea>(TD_CheckArealist);
                //添加仓库信息
                TD_CheckStor stordata = new TD_CheckStor();
                stordata.CheckId = data.Id;
                stordata.StorId = data.StorId;
                TD_CheckStorlist.Add(stordata);
                await Db.InsertAsync<TD_CheckStor>(TD_CheckStorlist);
            }
            else if (data.Type == "6")
            {
                //盘点类型货位
                //listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.StorId == data.StorId && x.LocalId == data.StorLocaId && data.ListIds.Contains(x.MaterialId)).ToListAsync();
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.StorId == data.StorId && x.LocalId == data.StorLocaId).ToListAsync();
                //添加货架信息
                TD_CheckRack rackdata = new TD_CheckRack();
                rackdata.CheckId = data.Id;
                rackdata.RackId = data.StorRackId;
                TD_CheckRacklist.Add(rackdata);
                await Db.InsertAsync<TD_CheckRack>(TD_CheckRacklist);
                //添加货位信息
                TD_CheckLoca locadata = new TD_CheckLoca();
                locadata.CheckId = data.Id;
                locadata.StorLocaId = data.StorLocaId;
                TD_CheckLocalist.Add(locadata);
                await Db.InsertAsync<TD_CheckLoca>(TD_CheckLocalist);
                //添加库区信息
                TD_CheckArea areadata = new TD_CheckArea();
                areadata.CherkId = data.Id;
                areadata.StoarAreaId = data.StorAreaId;
                TD_CheckArealist.Add(areadata);
                await Db.InsertAsync<TD_CheckArea>(TD_CheckArealist);
                //添加仓库信息
                TD_CheckStor stordata = new TD_CheckStor();
                stordata.CheckId = data.Id;
                stordata.StorId = data.StorId;
                TD_CheckStorlist.Add(stordata);
                await Db.InsertAsync<TD_CheckStor>(TD_CheckStorlist);

                var materlist = listdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                foreach (var item in materlist)
                {
                    TD_CheckMaterial materdata = new TD_CheckMaterial();
                    materdata.CheckId = data.Id;
                    materdata.MaterialId = item.MaterialId;
                    TD_CheckMateriallist.Add(materdata);
                }
                //添加物料信息
                await Db.InsertAsync<TD_CheckMaterial>(TD_CheckMateriallist);

            }

            if (data.Type != "3")
            {
                foreach (var item in listdata)
                {
                    TD_CheckData CheckData = new TD_CheckData();
                    CheckData.Id = IdHelper.GetId();
                    CheckData.CheckId = data.Id;
                    CheckData.StorId = item.StorId;
                    CheckData.localId = item.LocalId;
                    CheckData.MaterialId = item.MaterialId;
                    CheckData.LocalNum = (item.Nums_N + item.Nums_O);
                    CheckData.CheckNum = 0;
                    CheckData.DisNum = 0;
                    CheckData.CreateTime = data.CreateTime;
                    CheckData.CreatorId = data.CreatorId;
                    TD_CheckDatalist.Add(CheckData);
                }
                await Db.InsertAsync<TD_CheckData>(TD_CheckDatalist);
            }
            else if (data.Type == "3")
            {
                var materialdetail = listdata.GroupBy(x => new { x.MaterialId, x.StorId, x.LocalId }).Select(x => new { MaterialId = x.Key.MaterialId, StorId = x.Key.StorId, LocalId = x.Key.LocalId, Nums = x.Sum(i => i.ScanNum) }).ToList();
                foreach (var item in materialdetail)
                {
                    TD_CheckData CheckData = new TD_CheckData();
                    CheckData.Id = IdHelper.GetId();
                    CheckData.CheckId = data.Id;
                    CheckData.StorId = item.StorId;
                    CheckData.localId = item.LocalId;
                    CheckData.MaterialId = item.MaterialId;
                    CheckData.LocalNum = item.Nums;
                    CheckData.CheckNum = 0;
                    CheckData.DisNum = 0;
                    CheckData.CreateTime = data.CreateTime;
                    CheckData.CreatorId = data.CreatorId;
                    TD_CheckDatalist.Add(CheckData);
                }
                await Db.InsertAsync<TD_CheckData>(TD_CheckDatalist);
            }

            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
            TD_Check checkdatalist = new TD_Check();
            checkdatalist.Id = data.Id;
            checkdatalist.Code = sjtime;
            checkdatalist.CheckTime = data.CheckTime;
            checkdatalist.Type = data.Type;
            checkdatalist.IsComplete = false;
            checkdatalist.Status = 0;
            checkdatalist.CreateTime = data.CreateTime;
            checkdatalist.CreatorId = data.CreatorId;
            checkdatalist.Deleted = data.Deleted;
            checkdatalist.DeptId = userdata.FactoryId;
            checkdatalist.QrCode = h_cehck + "," + data.Id;
            checkdatalist.StorId = data.StorId;
            await Db.InsertAsync<TD_Check>(checkdatalist);
        }

        /// <summary>
        /// 盘点信息删除
        /// </summary>
        /// <param name="ids">盘点id集合</param>
        /// <returns></returns>
        [DataDeleteLog(UserLogType.盘点管理, "Code", "盘点单")]
        [Transactional]
        public async Task DeleteCheckAsync(List<string> ids)
        {

            string checkid = string.Empty;
            foreach (var item in ids)
            {
                checkid += "'" + item + "',";
            }
            checkid = checkid.Substring(0, checkid.Length - 1);
            string sqlMain = string.Empty;
            List<TD_Check> listdata = await Db.GetIQueryable<TD_Check>().Where(x => ids.Contains(x.Id) && x.Status >= 1).ToListAsync();
            if (listdata.Count > 0)
            {
                throw new BusException("审核通过的不能删除");
            }
            //删除盘点主表
            await Db.DeleteAsync<TD_Check>(ids);
            //删除盘点仓库信息
            sqlMain += @" DELETE from TD_CheckStor where CheckId in (" + checkid + "); ";
            //删除盘点货架信息
            sqlMain += @" DELETE from TD_CheckRack where CheckId in (" + checkid + "); ";
            //删除盘点货位信息
            sqlMain += @" DELETE from TD_CheckLoca where CheckId in (" + checkid + "); ";
            //删除盘点库区信息
            sqlMain += @" DELETE from TD_CheckArea where CherkId in (" + checkid + "); ";
            //删除盘点物料信息
            sqlMain += @" DELETE from TD_CheckMaterial where CheckId in (" + checkid + "); ";
            //删除盘点详细信息
            sqlMain += @" DELETE from TD_CheckData where CheckId in (" + checkid + "); ";
            //删除盘点详细信息
            sqlMain += @" DELETE from TD_CheckPack where CheckId in (" + checkid + "); ";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 盘点查看详细信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<TD_CheckDataDTO>> GetCheckDataAsync(PageInput<CheckConditionDTO> input)
        {
            var where = LinqHelper.True<TD_CheckDataDTO>();
            var search = input.Search;
            Expression<Func<TD_CheckData, PB_Material, Base_Department, PB_Location, PB_StorArea, PB_Rack, IT_LocalMaterial, TD_CheckDataDTO>> select = (a, b, c, d, e, f, g) => new TD_CheckDataDTO
            {
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSimpleName = b.SimpleName,
                MaterialSpec = b.Spec,
                StorName = c.Name,
                LocaName = e.Name + "/" + f.Name + "/" + d.Name,
                SanNums = g.ScanNum
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<TD_CheckData>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.StorId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Location>() on a.localId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_StorArea>() on d.AreaId equals e.Id into de
                    from e in de.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_Rack>() on d.RackId equals f.Id into df
                    from f in df.DefaultIfEmpty()
                    join g in Db.GetIQueryable<IT_LocalMaterial>() on new { StorId = a.StorId, localId = a.localId, MaterialId = a.MaterialId } equals new { StorId = g.StorId, localId = g.LocalId, MaterialId = g.MaterialId } into ag
                    from g in ag.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g);
            //筛选
            if (!search.checkId.IsNullOrEmpty())
            {
                where = where.And(x => x.CheckId == search.checkId);
            }
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 盘点单确定
        /// </summary>
        /// <param name="checkId">盘点单Id</param>
        /// <returns></returns>
        public async Task ToExamineCheckAsync(string checkId)
        {
            string sqlMain = @"update TD_Check set `Status`=1,ConfirmUserId='" + _operator.UserId + "',ConfirmTime=Now() where Id='" + checkId + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 盘点单审核
        /// </summary>
        /// <param name="checkId">盘点单Id</param>
        /// <returns></returns>
        public async Task ToReviewCheckAsync(string checkId)
        {
            string sqlMain = @"update TD_Check set `Status`=5,AuditUserId='" + _operator.UserId + "',AuditeTime=Now() where Id='" + checkId + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 盘点单开始盘点
        /// </summary>
        /// <param name="checkId">盘点单Id</param>
        /// <returns></returns>
        public async Task CheckStartAsync(string checkId)
        {
            string sqlMain = @"update TD_Check set `Status`=2 where Id='" + checkId + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 盘点完成
        /// </summary>
        /// <param name="checkId">盘点单Id</param>
        /// <returns></returns>
        public async Task UpdateInventoryCompleteAsync(string checkId)
        {
            ////查询是否有盘点数据
            //List<TD_CheckPack> CheckPacklist = await Db.GetIQueryable<TD_CheckPack>().Where(x => x.CheckId == checkId).ToListAsync();
            //if (CheckPacklist.Count > 0)
            //{
            //    //查询盘点单明细信息
            //    List<TD_CheckData> CheckDatalist = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == checkId).ToListAsync();
            //    //汇总盘点实时表数据
            //    var checkpack = CheckPacklist.GroupBy(x => new { x.MaterialId, x.StorId, x.localId }).Select(x => new { MaterialId = x.Key.MaterialId, StorId = x.Key.StorId, localId = x.Key.localId, Nums = x.Sum(i => i.Nums) }).ToList();
            //    string sqlMain = string.Empty;
            //    double? Difference = 0; ;
            //    foreach (var item in CheckDatalist)
            //    {
            //        var itemdata = checkpack.Where(x => x.MaterialId == item.MaterialId && x.StorId == item.StorId && x.localId == item.localId).FirstOrDefault();
            //        if (itemdata != null)
            //        {
            //            Difference = itemdata.Nums - item.LocalNum;
            //            sqlMain += @" UPDATE TD_CheckData set CheckNum=IFNULL(CheckNum,0)+" + itemdata.Nums + ",DisNum=IFNULL(DisNum,0)+" + Difference + " where Id='" + item.Id + "' and CheckId='" + checkId + "';  ";
            //        }
            //        else
            //        {
            //            Difference = 0 - item.LocalNum;
            //            sqlMain += @" UPDATE TD_CheckData set CheckNum=IFNULL(CheckNum,0)+0,DisNum=IFNULL(DisNum,0)+" + Difference + " where Id='" + item.Id + "' and CheckId='" + checkId + "';  ";
            //        }
            //    }
            //    await ExecuteSqlAsync(sqlMain);
            //    //修改盘点表状态为已完成
            //    sqlMain = @"update TD_Check set `Status`=3 where Id='" + checkId + "'";
            //    await ExecuteSqlAsync(sqlMain);
            //}
            //else
            //{
            //    throw new BusException("暂无盘点不能完成");
            //}

            //查询盘点单明细信息
            List<TD_CheckData> CheckDatalist = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == checkId).ToListAsync();
            //查询是否有盘点数据
            List<TD_CheckPack> CheckPacklist = await Db.GetIQueryable<TD_CheckPack>().Where(x => x.CheckId == checkId).ToListAsync();
            //汇总盘点实时表数据
            var checkpack = CheckPacklist.GroupBy(x => new { x.MaterialId, x.StorId, x.localId }).Select(x => new { MaterialId = x.Key.MaterialId, StorId = x.Key.StorId, localId = x.Key.localId, Nums = x.Sum(i => i.Nums) }).ToList();
            string sqlMain = string.Empty;
            double? Difference = 0; ;
            foreach (var item in CheckDatalist)
            {
                var itemdata = checkpack.Where(x => x.MaterialId == item.MaterialId && x.StorId == item.StorId && x.localId == item.localId).FirstOrDefault();
                if (itemdata != null)
                {
                    Difference = itemdata.Nums - item.LocalNum;
                    sqlMain += @" UPDATE TD_CheckData set CheckNum=IFNULL(CheckNum,0)+" + itemdata.Nums + ",DisNum=IFNULL(DisNum,0)+" + Difference + " where Id='" + item.Id + "' and CheckId='" + checkId + "';  ";
                }
                else
                {
                    Difference = 0 - item.LocalNum;
                    sqlMain += @" UPDATE TD_CheckData set CheckNum=IFNULL(CheckNum,0)+0,DisNum=IFNULL(DisNum,0)+" + Difference + " where Id='" + item.Id + "' and CheckId='" + checkId + "';  ";
                }
            }
            if (sqlMain.Length > 0)
            {
                await ExecuteSqlAsync(sqlMain);
            }
            //修改盘点表状态为已完成
            sqlMain = @"update TD_Check set `Status`=3 where Id='" + checkId + "'";
            await ExecuteSqlAsync(sqlMain);

        }

        /// <summary>
        /// 获取盘点明细信息
        /// </summary>
        /// <param name="checkId">盘点单Id</param>
        /// <returns></returns>
        public async Task<List<TD_CheckData>> GetCheckDataListAsync(string checkId)
        {
            List<TD_CheckData> CheckData = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == checkId).ToListAsync();
            return CheckData;
        }

        /// <summary>
        /// 获取实际盘点信息
        /// </summary>
        /// <param name="checkId">盘点单Id</param>
        /// <returns></returns>
        public async Task<List<TD_CheckPack>> GetCheckPackAsync(string checkId)
        {
            List<TD_CheckPack> CheckPack = await Db.GetIQueryable<TD_CheckPack>().Where(x => x.CheckId == checkId).ToListAsync();
            return CheckPack;
        }

        /// <summary>
        /// 获取库存物料信息
        /// </summary>
        /// <param name="data">盘点明细</param>
        /// <returns></returns>
        public async Task<StorMaterialDTO> GetStorMaterialListAsync(TDcheckDataDTO data)
        {
            StorMaterialDTO stordata = new StorMaterialDTO();
            if (data.CheckData.Count > 0)
            {
                var check = data.CheckData.GroupBy(x => new { x.CheckId }).Select(x => new { CheckId = x.Key.CheckId }).FirstOrDefault();

                TD_Check tdcheck = await Db.GetIQueryable<TD_Check>().Where(x => x.Id == check.CheckId).FirstOrDefaultAsync();
                //获取盘差值为整数的明细的货位信息
                var pnlocadata = data.CheckData.GroupBy(x => new { x.localId }).Select(x => new { localId = x.Key.localId }).ToList();
                List<string> locaIds = new List<string>();
                foreach (var item in pnlocadata)
                {
                    locaIds.Add(item.localId);
                }
                //获取盘差值为整数的明细的物料信息
                var material = data.CheckData.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                List<string> materialIds = new List<string>();
                foreach (var item in material)
                {
                    materialIds.Add(item.MaterialId);
                }
                //获取库存明细信息
                List<IT_LocalDetail> LocalDetaillist = await Db.GetIQueryable<IT_LocalDetail>().Where(x => locaIds.Contains(x.LocalId) && materialIds.Contains(x.MaterialId) && x.CreateTime < tdcheck.CreateTime).ToListAsync();

                //获取库存汇总信息
                List<IT_LocalMaterial> LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => locaIds.Contains(x.LocalId) && materialIds.Contains(x.MaterialId)).ToListAsync();

                //获取PB_Stock信息
                List<PB_Stock> PB_Stocklist = await Db.GetIQueryable<PB_Stock>().Where(x => locaIds.Contains(x.LocationId) && materialIds.Contains(x.MaterialId) && x.PackId == "" && x.CreateTime < tdcheck.CreateTime).ToListAsync();

                //获取物料信息
                List<PB_Material> Materiallist = await Db.GetIQueryable<PB_Material>().Where(x => materialIds.Contains(x.Id)).ToListAsync();

                stordata.LocalDetailList = LocalDetaillist;
                stordata.LocalMaterialList = LocalMaterial;
                stordata.MaterialList = Materiallist;
                stordata.StockList = PB_Stocklist;
            }
            return stordata;
        }

        /// <summary>
        /// 计算盘差值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<DiscDifferenceDTO> GetDiscDifferenceAsync(DifferenceDTO data)
        {
            Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");
            string sqlMain = string.Empty;
            DiscDifferenceDTO dddata = new DiscDifferenceDTO();
            if (data.CheckData.Count > 0)
            {
                List<IT_LocalDetail> itdata = new List<IT_LocalDetail>();
                List<PB_Stock> Stock = new List<PB_Stock>();
                List<PB_StockLog> StockLog = new List<PB_StockLog>();
                List<TD_InStorDetail> InStorDetail = new List<TD_InStorDetail>();
                List<TD_OutStorDetail> OutStorDetail = new List<TD_OutStorDetail>();
                Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
                //获取盘点单对应的仓库
                List<TD_CheckStor> CheckStor = await Db.GetIQueryable<TD_CheckStor>().Where(x => x.CheckId == data.checkId).ToListAsync();
                //获取库存明细
                List<IT_LocalDetail> LocalDetaillist = data.LocalDetailList;
                //获取物料信息
                List<PB_Material> Materiallist = data.MaterialList;

                foreach (var itemstor in CheckStor)
                {
                    //盘差值为正数
                    #region
                    var PositiveNumber = data.CheckData.Where(x => x.StorId == itemstor.StorId && x.DisNum > 0).ToList();

                    if (PositiveNumber.Count > 0)
                    {
                        string pickids = "";
                        //入库单Id
                        string InId = IdHelper.GetId();

                        foreach (var item in PositiveNumber)
                        {
                            //查询实际盘点的
                            var checkpackdata = data.CheckPack.Where(x => x.StorId == itemstor.StorId && x.localId == item.localId && x.MaterialId == item.MaterialId).ToList();
                            foreach (var itemdata in checkpackdata)
                            {
                                if (!itemdata.PackId.IsNullOrEmpty())
                                {
                                    //根据实际盘点查询库存明细的
                                    var materdata = LocalDetaillist.Where(x => x.StorId == itemstor.StorId && x.LocalId == item.localId && x.MaterialId == item.MaterialId && x.PackId == itemdata.PackId).FirstOrDefault();
                                    if (materdata == null)
                                    {
                                        PB_Stock st = new PB_Stock();
                                        st.Id = IdHelper.GetId();
                                        st.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        st.StorId = itemdata.StorId;
                                        st.LocationId = itemdata.localId;
                                        st.StockNumber = itemdata.Nums;
                                        st.MaterialId = itemdata.MaterialId;
                                        st.CreatorId = _operator.UserId;
                                        st.CreatorName = userdata.RealName;
                                        st.CreateTime = DateTime.Now;
                                        st.Type = 1;
                                        st.OldOrNew = itemdata.OldOrNew;
                                        st.JobId = "";
                                        Stock.Add(st);

                                        PB_StockLog log = new PB_StockLog();
                                        log.Id = IdHelper.GetId();
                                        log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        log.MaterialId = itemdata.MaterialId;
                                        log.StorId = itemdata.StorId;
                                        log.LocationId = itemdata.localId;
                                        log.StockNumber = itemdata.Nums;
                                        log.CreatorId = _operator.UserId;
                                        log.Deleted = false;
                                        log.CreatorName = userdata.RealName;
                                        log.OperatorId = _operator.UserId;
                                        log.Type = 1;
                                        log.CreateTime = DateTime.Now;
                                        log.State = 0;
                                        log.OldOrNew = itemdata.OldOrNew;
                                        log.JobId = "";
                                        StockLog.Add(log);

                                        IT_LocalDetail itdet = new IT_LocalDetail();
                                        itdet.Id = IdHelper.GetId();
                                        itdet.StorId = itemdata.StorId;
                                        itdet.LocalId = itemdata.localId;
                                        itdet.MaterialId = itemdata.MaterialId;
                                        itdet.InTime = DateTime.Now;
                                        itdet.CreateTime = DateTime.Now;
                                        itdet.CreatorId = _operator.UserId;
                                        itdet.Deleted = false;
                                        itdet.Num = itemdata.Nums;
                                        itdet.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        itdet.OldOrNew = itemdata.OldOrNew;
                                        itdet.RecId = "";
                                        itdet.JobId = "";
                                        itdata.Add(itdet);

                                        var Material = Materiallist.Where(x => x.Id == itemdata.MaterialId).FirstOrDefault();

                                        //入库单明细
                                        TD_InStorDetail Instord = new TD_InStorDetail();
                                        Instord.Id = IdHelper.GetId();
                                        Instord.InStorId = InId;
                                        Instord.StorId = itemdata.StorId;
                                        Instord.LocalId = itemdata.localId;
                                        Instord.MaterialId = itemdata.MaterialId;
                                        Instord.Price = Convert.ToDouble(Material.Price);
                                        Instord.TotalAmt = Convert.ToDouble(Material.Price * itemdata.Nums);
                                        Instord.Num = Convert.ToDouble(itemdata.Nums);
                                        Instord.CreatorId = _operator.UserId;
                                        Instord.CreateTime = DateTime.Now;
                                        Instord.Deleted = false;
                                        Instord.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        Instord.OldOrNew = itemdata.OldOrNew;
                                        Instord.JobId = "";
                                        InStorDetail.Add(Instord);

                                        pickids += "'" + itemdata.PackId + "',";

                                    }
                                }
                                else
                                {
                                    if (linktypedata.Whether == true)
                                    {
                                        //根据实际盘点查询库存明细的
                                        var materdata = LocalDetaillist.Where(x => x.StorId == itemstor.StorId && x.LocalId == item.localId && x.MaterialId == item.MaterialId).ToList();
                                        var mater = materdata.GroupBy(x => new { x.StorId, x.LocalId, x.MaterialId, x.JobId }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, JobId = x.Key.JobId, Num = x.Sum(i => i.Num) }).FirstOrDefault();

                                        PB_Stock st = new PB_Stock();
                                        st.Id = IdHelper.GetId();
                                        st.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        st.StorId = itemdata.StorId;
                                        st.LocationId = itemdata.localId;
                                        st.StockNumber = (itemdata.Nums - (mater == null ? 0 : mater.Num));
                                        st.MaterialId = itemdata.MaterialId;
                                        st.CreatorId = _operator.UserId;
                                        st.CreatorName = userdata.RealName;
                                        st.CreateTime = DateTime.Now;
                                        st.Type = 1;
                                        st.OldOrNew = itemdata.OldOrNew;
                                        st.JobId = itemdata.JobId;
                                        Stock.Add(st);

                                        PB_StockLog log = new PB_StockLog();
                                        log.Id = IdHelper.GetId();
                                        log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        log.MaterialId = itemdata.MaterialId;
                                        log.StorId = itemdata.StorId;
                                        log.LocationId = itemdata.localId;
                                        log.StockNumber = (itemdata.Nums - (mater == null ? 0 : mater.Num));
                                        log.CreatorId = _operator.UserId;
                                        log.Deleted = false;
                                        log.CreatorName = userdata.RealName;
                                        log.OperatorId = _operator.UserId;
                                        log.Type = 1;
                                        log.CreateTime = DateTime.Now;
                                        log.State = 0;
                                        log.OldOrNew = itemdata.OldOrNew;
                                        log.JobId = itemdata.JobId;
                                        StockLog.Add(log);

                                        IT_LocalDetail itdet = new IT_LocalDetail();
                                        itdet.Id = IdHelper.GetId();
                                        itdet.StorId = itemdata.StorId;
                                        itdet.LocalId = itemdata.localId;
                                        itdet.MaterialId = itemdata.MaterialId;
                                        itdet.InTime = DateTime.Now;
                                        itdet.CreateTime = DateTime.Now;
                                        itdet.CreatorId = _operator.UserId;
                                        itdet.Deleted = false;
                                        itdet.Num = (itemdata.Nums - (mater == null ? 0 : mater.Num));
                                        itdet.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        itdet.OldOrNew = itemdata.OldOrNew;
                                        itdet.RecId = "";
                                        itdet.JobId = itemdata.JobId;
                                        itdata.Add(itdet);

                                        var Material = Materiallist.Where(x => x.Id == itemdata.MaterialId).FirstOrDefault();

                                        //入库单明细
                                        TD_InStorDetail Instord = new TD_InStorDetail();
                                        Instord.Id = IdHelper.GetId();
                                        Instord.InStorId = InId;
                                        Instord.StorId = itemdata.StorId;
                                        Instord.LocalId = itemdata.localId;
                                        Instord.MaterialId = itemdata.MaterialId;
                                        Instord.Price = Convert.ToDouble(Material.Price);
                                        Instord.TotalAmt = Convert.ToDouble(Material.Price * (itemdata.Nums - (mater == null ? 0 : mater.Num)));
                                        Instord.Num = Convert.ToDouble(itemdata.Nums - (mater == null ? 0 : mater.Num));
                                        Instord.CreatorId = _operator.UserId;
                                        Instord.CreateTime = DateTime.Now;
                                        Instord.Deleted = false;
                                        Instord.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        Instord.OldOrNew = itemdata.OldOrNew;
                                        Instord.JobId = itemdata.JobId;
                                        InStorDetail.Add(Instord);
                                    }
                                    else
                                    {
                                        //根据实际盘点查询库存明细的
                                        var materdata = LocalDetaillist.Where(x => x.StorId == itemstor.StorId && x.LocalId == item.localId && x.MaterialId == item.MaterialId).ToList();
                                        var mater = materdata.GroupBy(x => new { x.StorId, x.LocalId, x.MaterialId, x.JobId }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, Num = x.Sum(i => i.Num) }).FirstOrDefault();

                                        PB_Stock st = new PB_Stock();
                                        st.Id = IdHelper.GetId();
                                        st.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        st.StorId = itemdata.StorId;
                                        st.LocationId = itemdata.localId;
                                        st.StockNumber = (itemdata.Nums - (mater == null ? 0 : mater.Num));
                                        st.MaterialId = itemdata.MaterialId;
                                        st.CreatorId = _operator.UserId;
                                        st.CreatorName = userdata.RealName;
                                        st.CreateTime = DateTime.Now;
                                        st.Type = 1;
                                        st.OldOrNew = itemdata.OldOrNew;
                                        st.JobId = "";
                                        Stock.Add(st);

                                        PB_StockLog log = new PB_StockLog();
                                        log.Id = IdHelper.GetId();
                                        log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        log.MaterialId = itemdata.MaterialId;
                                        log.StorId = itemdata.StorId;
                                        log.LocationId = itemdata.localId;
                                        log.StockNumber = (itemdata.Nums - (mater == null ? 0 : mater.Num));
                                        log.CreatorId = _operator.UserId;
                                        log.Deleted = false;
                                        log.CreatorName = userdata.RealName;
                                        log.OperatorId = _operator.UserId;
                                        log.Type = 1;
                                        log.CreateTime = DateTime.Now;
                                        log.State = 0;
                                        log.OldOrNew = itemdata.OldOrNew;
                                        log.JobId = "";
                                        StockLog.Add(log);

                                        IT_LocalDetail itdet = new IT_LocalDetail();
                                        itdet.Id = IdHelper.GetId();
                                        itdet.StorId = itemdata.StorId;
                                        itdet.LocalId = itemdata.localId;
                                        itdet.MaterialId = itemdata.MaterialId;
                                        itdet.InTime = DateTime.Now;
                                        itdet.CreateTime = DateTime.Now;
                                        itdet.CreatorId = _operator.UserId;
                                        itdet.Deleted = false;
                                        itdet.Num = (itemdata.Nums - (mater == null ? 0 : mater.Num));
                                        itdet.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        itdet.OldOrNew = itemdata.OldOrNew;
                                        itdet.RecId = "";
                                        itdet.JobId = "";
                                        itdata.Add(itdet);

                                        var Material = Materiallist.Where(x => x.Id == itemdata.MaterialId).FirstOrDefault();

                                        //入库单明细
                                        TD_InStorDetail Instord = new TD_InStorDetail();
                                        Instord.Id = IdHelper.GetId();
                                        Instord.InStorId = InId;
                                        Instord.StorId = itemdata.StorId;
                                        Instord.LocalId = itemdata.localId;
                                        Instord.MaterialId = itemdata.MaterialId;
                                        Instord.Price = Convert.ToDouble(Material.Price);
                                        Instord.TotalAmt = Convert.ToDouble(Material.Price * (itemdata.Nums - (mater == null ? 0 : mater.Num)));
                                        Instord.Num = Convert.ToDouble(itemdata.Nums - (mater == null ? 0 : mater.Num));
                                        Instord.CreatorId = _operator.UserId;
                                        Instord.CreateTime = DateTime.Now;
                                        Instord.Deleted = false;
                                        Instord.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        Instord.OldOrNew = itemdata.OldOrNew;
                                        Instord.JobId = "";
                                        InStorDetail.Add(Instord);
                                    }
                                }
                            }
                        }
                        if (pickids.Length > 0)
                        {
                            sqlMain += @" update PB_PackList set Status = 3, InStorTime = NOW(),OutStorTime=NULL where Id  in (" + pickids.Substring(0, pickids.Length - 1) + ");";
                        }
                    }
                    #endregion

                    //盘差值为负数
                    #region
                    var negative = data.CheckData.Where(x => x.StorId == itemstor.StorId && x.DisNum < 0).ToList();

                    if (negative.Count > 0)
                    {
                        string pickids = "";

                        //出库单Id
                        string outId = IdHelper.GetId();
                        foreach (var item in negative)
                        {
                            double? disnum = -item.DisNum;
                            //查询库存明细包的信息
                            var packlist = LocalDetaillist.Where(x => x.StorId == item.StorId && x.LocalId == item.localId && x.MaterialId == item.MaterialId && x.PackId != "").ToList();
                            if (packlist.Count > 0)
                            {
                                foreach (var itemdata in packlist)
                                {
                                    //查询实际盘点数据
                                    var checkpackdata = data.CheckPack.Where(x => x.StorId == itemdata.StorId && x.localId == itemdata.LocalId && x.MaterialId == itemdata.MaterialId && x.PackId == itemdata.PackId).FirstOrDefault();
                                    var materdata = Materiallist.Where(x => x.Id == itemdata.MaterialId).FirstOrDefault();
                                    if (checkpackdata == null)
                                    {
                                        //出库单明细
                                        TD_OutStorDetail outdetail = new TD_OutStorDetail();
                                        outdetail.Id = IdHelper.GetId();
                                        outdetail.StorId = item.StorId;
                                        outdetail.OutStorId = outId;
                                        outdetail.LocalId = itemdata.LocalId;
                                        outdetail.MaterialId = item.MaterialId;
                                        outdetail.OutNum = Convert.ToDouble(itemdata
                                            .Num);
                                        outdetail.Price = Convert.ToDouble(materdata.Price);
                                        outdetail.TotalAmt = Convert.ToDouble(materdata.Price * itemdata
                                            .Num);
                                        outdetail.CreateTime = DateTime.Now;
                                        outdetail.CreatorId = _operator.UserId;
                                        outdetail.Deleted = false;
                                        outdetail.OldOrNew = itemdata.OldOrNew;
                                        OutStorDetail.Add(outdetail);

                                        PB_StockLog log = new PB_StockLog();
                                        log.Id = IdHelper.GetId();
                                        log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                        log.MaterialId = item.MaterialId;
                                        log.StorId = item.StorId;
                                        log.LocationId = itemdata.LocalId;
                                        log.StockNumber = itemdata.Num;
                                        log.CreatorId = _operator.UserId;
                                        log.Deleted = false;
                                        log.CreatorName = userdata.RealName;
                                        log.OperatorId = _operator.UserId;
                                        log.Type = 1;
                                        log.CreateTime = DateTime.Now;
                                        log.State = 1;
                                        log.OldOrNew = itemdata.OldOrNew;
                                        StockLog.Add(log);
                                        pickids += "'" + itemdata.PackId + "',";
                                    }
                                }
                            }

                            //查询库存明细单个物料信息
                            var materlist = LocalDetaillist.Where(x => x.StorId == item.StorId && x.LocalId == item.localId && x.MaterialId == item.MaterialId && x.PackId == "").ToList();
                            if (materlist.Count > 0)
                            {
                                var materdata = Materiallist.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                                foreach (var itemdata in materlist)
                                {
                                    if (disnum != 0)
                                    {
                                        if (linktypedata.Whether == true)
                                        {
                                            if (!itemdata.JobId.IsNullOrEmpty())
                                            {
                                                var checkjobdata = data.CheckPack.Where(x => x.StorId == itemdata.StorId && x.localId == itemdata.LocalId && x.MaterialId == itemdata.MaterialId && x.JobId == itemdata.JobId).FirstOrDefault();
                                                if (checkjobdata == null)
                                                {
                                                    sqlMain += @" delete from IT_LocalDetail where Id='" + itemdata.Id + "'; ";
                                                    //出库单明细
                                                    TD_OutStorDetail outdetail = new TD_OutStorDetail();
                                                    outdetail.Id = IdHelper.GetId();
                                                    outdetail.StorId = item.StorId;
                                                    outdetail.OutStorId = outId;
                                                    outdetail.LocalId = itemdata.LocalId;
                                                    outdetail.MaterialId = item.MaterialId;
                                                    outdetail.OutNum = Convert.ToDouble(disnum);
                                                    outdetail.Price = Convert.ToDouble(materdata.Price);
                                                    outdetail.TotalAmt = Convert.ToDouble(materdata.Price * disnum);
                                                    outdetail.CreateTime = DateTime.Now;
                                                    outdetail.CreatorId = _operator.UserId;
                                                    outdetail.Deleted = false;
                                                    outdetail.OldOrNew = itemdata.OldOrNew;
                                                    OutStorDetail.Add(outdetail);

                                                    PB_StockLog log = new PB_StockLog();
                                                    log.Id = IdHelper.GetId();
                                                    log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                                    log.MaterialId = item.MaterialId;
                                                    log.StorId = item.StorId;
                                                    log.LocationId = itemdata.LocalId;
                                                    log.StockNumber = itemdata.Num;
                                                    log.CreatorId = _operator.UserId;
                                                    log.Deleted = false;
                                                    log.CreatorName = userdata.RealName;
                                                    log.OperatorId = _operator.UserId;
                                                    log.Type = 1;
                                                    log.CreateTime = DateTime.Now;
                                                    log.State = 1;
                                                    log.OldOrNew = itemdata.OldOrNew;
                                                    log.JobId = itemdata.JobId;
                                                    StockLog.Add(log);
                                                    disnum -= 1;
                                                }
                                            }
                                            else
                                            {
                                                if (disnum < itemdata.Num)
                                                {
                                                    sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + disnum + " where Id='" + itemdata.Id + "'; ";

                                                    //出库单明细
                                                    TD_OutStorDetail outdetail = new TD_OutStorDetail();
                                                    outdetail.Id = IdHelper.GetId();
                                                    outdetail.StorId = item.StorId;
                                                    outdetail.OutStorId = outId;
                                                    outdetail.LocalId = itemdata.LocalId;
                                                    outdetail.MaterialId = item.MaterialId;
                                                    outdetail.OutNum = Convert.ToDouble(disnum);
                                                    outdetail.Price = Convert.ToDouble(materdata.Price);
                                                    outdetail.TotalAmt = Convert.ToDouble(materdata.Price * disnum);
                                                    outdetail.CreateTime = DateTime.Now;
                                                    outdetail.CreatorId = _operator.UserId;
                                                    outdetail.Deleted = false;
                                                    outdetail.OldOrNew = itemdata.OldOrNew;
                                                    OutStorDetail.Add(outdetail);

                                                    PB_StockLog log = new PB_StockLog();
                                                    log.Id = IdHelper.GetId();
                                                    log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                                    log.MaterialId = item.MaterialId;
                                                    log.StorId = item.StorId;
                                                    log.LocationId = itemdata.LocalId;
                                                    log.StockNumber = itemdata.Num;
                                                    log.CreatorId = _operator.UserId;
                                                    log.Deleted = false;
                                                    log.CreatorName = userdata.RealName;
                                                    log.OperatorId = _operator.UserId;
                                                    log.Type = 1;
                                                    log.CreateTime = DateTime.Now;
                                                    log.State = 1;
                                                    log.OldOrNew = itemdata.OldOrNew;
                                                    log.JobId = "";
                                                    StockLog.Add(log);
                                                    disnum -= disnum;
                                                }
                                                else if (disnum >= itemdata.Num)
                                                {
                                                    sqlMain += @" delete from IT_LocalDetail where Id='" + itemdata.Id + "'; ";

                                                    //出库单明细
                                                    TD_OutStorDetail outdetail = new TD_OutStorDetail();
                                                    outdetail.Id = IdHelper.GetId();
                                                    outdetail.StorId = item.StorId;
                                                    outdetail.OutStorId = outId;
                                                    outdetail.LocalId = itemdata.LocalId;
                                                    outdetail.MaterialId = item.MaterialId;
                                                    outdetail.OutNum = Convert.ToDouble(itemdata.Num);
                                                    outdetail.Price = Convert.ToDouble(materdata.Price);
                                                    outdetail.TotalAmt = Convert.ToDouble(materdata.Price * itemdata.Num);
                                                    outdetail.CreateTime = DateTime.Now;
                                                    outdetail.CreatorId = _operator.UserId;
                                                    outdetail.Deleted = false;
                                                    outdetail.OldOrNew = itemdata.OldOrNew;
                                                    OutStorDetail.Add(outdetail);

                                                    PB_StockLog log = new PB_StockLog();
                                                    log.Id = IdHelper.GetId();
                                                    log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                                    log.MaterialId = item.MaterialId;
                                                    log.StorId = item.StorId;
                                                    log.LocationId = itemdata.LocalId;
                                                    log.StockNumber = itemdata.Num;
                                                    log.CreatorId = _operator.UserId;
                                                    log.Deleted = false;
                                                    log.CreatorName = userdata.RealName;
                                                    log.OperatorId = _operator.UserId;
                                                    log.Type = 1;
                                                    log.CreateTime = DateTime.Now;
                                                    log.State = 1;
                                                    log.OldOrNew = itemdata.OldOrNew;
                                                    log.JobId = "";
                                                    StockLog.Add(log);
                                                    disnum -= itemdata.Num;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (disnum < itemdata.Num)
                                            {
                                                sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + disnum + " where Id='" + itemdata.Id + "'; ";

                                                //出库单明细
                                                TD_OutStorDetail outdetail = new TD_OutStorDetail();
                                                outdetail.Id = IdHelper.GetId();
                                                outdetail.StorId = item.StorId;
                                                outdetail.OutStorId = outId;
                                                outdetail.LocalId = itemdata.LocalId;
                                                outdetail.MaterialId = item.MaterialId;
                                                outdetail.OutNum = Convert.ToDouble(disnum);
                                                outdetail.Price = Convert.ToDouble(materdata.Price);
                                                outdetail.TotalAmt = Convert.ToDouble(materdata.Price * disnum);
                                                outdetail.CreateTime = DateTime.Now;
                                                outdetail.CreatorId = _operator.UserId;
                                                outdetail.Deleted = false;
                                                outdetail.OldOrNew = itemdata.OldOrNew;
                                                OutStorDetail.Add(outdetail);

                                                PB_StockLog log = new PB_StockLog();
                                                log.Id = IdHelper.GetId();
                                                log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                                log.MaterialId = item.MaterialId;
                                                log.StorId = item.StorId;
                                                log.LocationId = itemdata.LocalId;
                                                log.StockNumber = itemdata.Num;
                                                log.CreatorId = _operator.UserId;
                                                log.Deleted = false;
                                                log.CreatorName = userdata.RealName;
                                                log.OperatorId = _operator.UserId;
                                                log.Type = 1;
                                                log.CreateTime = DateTime.Now;
                                                log.State = 1;
                                                log.OldOrNew = itemdata.OldOrNew;
                                                log.JobId = "";
                                                StockLog.Add(log);
                                                disnum -= disnum;
                                            }
                                            else if (disnum >= itemdata.Num)
                                            {
                                                sqlMain += @" delete from IT_LocalDetail where Id='" + itemdata.Id + "'; ";

                                                //出库单明细
                                                TD_OutStorDetail outdetail = new TD_OutStorDetail();
                                                outdetail.Id = IdHelper.GetId();
                                                outdetail.StorId = item.StorId;
                                                outdetail.OutStorId = outId;
                                                outdetail.LocalId = itemdata.LocalId;
                                                outdetail.MaterialId = item.MaterialId;
                                                outdetail.OutNum = Convert.ToDouble(itemdata.Num);
                                                outdetail.Price = Convert.ToDouble(materdata.Price);
                                                outdetail.TotalAmt = Convert.ToDouble(materdata.Price * itemdata.Num);
                                                outdetail.CreateTime = DateTime.Now;
                                                outdetail.CreatorId = _operator.UserId;
                                                outdetail.Deleted = false;
                                                outdetail.OldOrNew = itemdata.OldOrNew;
                                                OutStorDetail.Add(outdetail);

                                                PB_StockLog log = new PB_StockLog();
                                                log.Id = IdHelper.GetId();
                                                log.PackId = itemdata.PackId == null ? "" : itemdata.PackId;
                                                log.MaterialId = item.MaterialId;
                                                log.StorId = item.StorId;
                                                log.LocationId = itemdata.LocalId;
                                                log.StockNumber = itemdata.Num;
                                                log.CreatorId = _operator.UserId;
                                                log.Deleted = false;
                                                log.CreatorName = userdata.RealName;
                                                log.OperatorId = _operator.UserId;
                                                log.Type = 1;
                                                log.CreateTime = DateTime.Now;
                                                log.State = 1;
                                                log.OldOrNew = itemdata.OldOrNew;
                                                log.JobId = "";
                                                StockLog.Add(log);
                                                disnum -= itemdata.Num;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (!pickids.IsNullOrEmpty())
                        {
                            sqlMain += @" delete from IT_LocalDetail where PackId in (" + pickids.Substring(0, pickids.Length - 1) + ");";
                            sqlMain += @" delete from PB_Stock where PackId in (" + pickids.Substring(0, pickids.Length - 1) + ");";
                            sqlMain += @" update PB_PackList set Status = 4, OutStorTime = NOW() where Id  in (" + pickids.Substring(0, pickids.Length - 1) + ");";
                        }
                    }
                    List<PB_Stock> PB_Stocklist = data.StockList;

                    #endregion

                }
                dddata.StockList = Stock;
                dddata.StockLog = StockLog;
                dddata.itdata = itdata;
                dddata.InStorDetail = InStorDetail;
                dddata.OutStorDetail = OutStorDetail;
                dddata.SqlMain = sqlMain;
            }
            return dddata;
        }

        /// <summary>
        /// 盘差
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task UpDifferenceAsync(DifferenceDTO data)
        {
            ////查询盘点明细
            //List<TD_CheckData> CheckData = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == checkId && x.DisNum != 0).ToListAsync();
            ////获取实际盘点明细
            //List<TD_CheckPack> CheckPack = await Db.GetIQueryable<TD_CheckPack>().Where(x => x.CheckId == checkId).ToListAsync();
            ////获取盘点单对应的仓库
            //List<TD_CheckStor> CheckStor = await Db.GetIQueryable<TD_CheckStor>().Where(x => x.CheckId == checkId).ToListAsync();
            ////获取盘差值为整数的明细的货位信息
            //var pnlocadata = CheckData.GroupBy(x => new { x.localId }).Select(x => new { localId = x.Key.localId }).ToList();
            //List<string> locaIds = new List<string>();
            //foreach (var item in pnlocadata)
            //{
            //    locaIds.Add(item.localId);
            //}
            ////获取盘差值为整数的明细的物料信息
            //var material = CheckData.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
            //List<string> materialIds = new List<string>();
            //foreach (var item in material)
            //{
            //    materialIds.Add(item.MaterialId);
            //}
            ////获取库存明细信息
            //List<IT_LocalDetail> LocalDetaillist = await Db.GetIQueryable<IT_LocalDetail>().Where(x => locaIds.Contains(x.LocalId) && materialIds.Contains(x.MaterialId)).ToListAsync();

            ////获取库存汇总信息
            //List<IT_LocalMaterial> LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => locaIds.Contains(x.LocalId) && materialIds.Contains(x.MaterialId)).ToListAsync();
            if (data.CheckData.Count > 0)
            {

                Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                //List<PB_Material> Materiallist = await Db.GetIQueryable<PB_Material>().Where(x => materialIds.Contains(x.Id)).ToListAsync();

                //获取盘点单对应的仓库
                //List<TD_CheckStor> CheckStor = await Db.GetIQueryable<TD_CheckStor>().Where(x => x.CheckId == data.checkId).ToListAsync();
                //获取库存明细
                //List<IT_LocalDetail> LocalDetaillist = data.LocalDetailList;
                //获取库存汇总
                List<IT_LocalMaterial> LocalMaterial = data.LocalMaterialList;
                List<TD_InStorDetail> InStorDetail = data.InStorDetail;
                List<TD_OutStorDetail> OutStorDetail = data.OutStorDetail;
                //获取物料信息
                //List<PB_Material> Materiallist = data.MaterialList;

                List<TD_InStorage> InStorage = new List<TD_InStorage>();
                List<TD_InStorRecord> InStorRecord = new List<TD_InStorRecord>();
                List<TD_OutStorage> OutStorage = new List<TD_OutStorage>();
                List<TD_OutStorRecord> OutStorRecord = new List<TD_OutStorRecord>();
                //string sqlMain = string.Empty;
                string outsql = string.Empty;
                #region
                //foreach (var itemstor in CheckStor)
                //{
                //    //盘差值为正数
                //    #region
                //    var PositiveNumber = data.CheckData.Where(x => x.StorId == itemstor.StorId && x.DisNum > 0).ToList();

                //    if (PositiveNumber.Count > 0)
                //    {
                //        List<string> packids = new List<string>();
                //        //入库单Id
                //        string InId = IdHelper.GetId();

                //        //计算包
                //        foreach (var item in PositiveNumber)
                //        {
                //            //获取当前物料实际盘点包的数据
                //            var itemdata = data.CheckPack.Where(x => x.StorId == itemstor.StorId && x.localId == item.localId && x.MaterialId == item.MaterialId && x.PackId != "").ToList();
                //            //获取当前物料库存明细包的数据
                //            var LocalDetail = LocalDetaillist.Where(x => x.StorId == itemstor.StorId && x.LocalId == item.localId && x.MaterialId == item.MaterialId && x.PackId != "").ToList();
                //            //当前仓库货位实际盘点包比当前仓库货位库存包多
                //            foreach (var sitem in itemdata)
                //            {
                //                var locapack = LocalDetail.Where(x => x.PackId == sitem.PackId).FirstOrDefault();
                //                if (locapack == null)
                //                {
                //                    PB_Stock st = new PB_Stock();
                //                    st.Id = IdHelper.GetId();
                //                    st.PackId = sitem.PackId;
                //                    st.StorId = sitem.StorId;
                //                    st.LocationId = sitem.localId;
                //                    st.StockNumber = sitem.Nums;
                //                    st.MaterialId = sitem.MaterialId;
                //                    st.CreatorId = _operator.UserId;
                //                    st.CreatorName = userdata.RealName;
                //                    st.CreateTime = DateTime.Now;
                //                    st.Type = 1;
                //                    st.OldOrNew = sitem.OldOrNew;
                //                    Stock.Add(st);

                //                    PB_StockLog log = new PB_StockLog();
                //                    log.Id = IdHelper.GetId();
                //                    log.PackId = sitem.PackId;
                //                    log.MaterialId = sitem.MaterialId;
                //                    log.StorId = sitem.StorId;
                //                    log.LocationId = sitem.localId;
                //                    log.StockNumber = sitem.Nums;
                //                    log.CreatorId = _operator.UserId;
                //                    log.Deleted = false;
                //                    log.CreatorName = userdata.RealName;
                //                    log.OperatorId = _operator.UserId;
                //                    log.Type = 1;
                //                    log.CreateTime = DateTime.Now;
                //                    log.State = 0;
                //                    log.OldOrNew = sitem.OldOrNew;
                //                    StockLog.Add(log);

                //                    IT_LocalDetail itdet = new IT_LocalDetail();
                //                    itdet.Id = IdHelper.GetId();
                //                    itdet.StorId = sitem.StorId;
                //                    itdet.LocalId = sitem.localId;
                //                    itdet.MaterialId = sitem.MaterialId;
                //                    itdet.InTime = DateTime.Now;
                //                    itdet.CreateTime = DateTime.Now;
                //                    itdet.CreatorId = _operator.UserId;
                //                    itdet.Deleted = false;
                //                    itdet.Num = sitem.Nums;
                //                    itdet.PackId = sitem.PackId;
                //                    itdet.OldOrNew = sitem.OldOrNew;
                //                    itdet.RecId = "";
                //                    itdata.Add(itdet);

                //                    var materdata = Materiallist.Where(x => x.Id == sitem.MaterialId).FirstOrDefault();

                //                    //入库单明细
                //                    TD_InStorDetail Instord = new TD_InStorDetail();
                //                    Instord.Id = IdHelper.GetId();
                //                    Instord.InStorId = InId;
                //                    Instord.StorId = sitem.StorId;
                //                    Instord.LocalId = sitem.localId;
                //                    Instord.MaterialId = sitem.MaterialId;
                //                    Instord.Price = Convert.ToDouble(materdata.Price);
                //                    Instord.TotalAmt = Convert.ToDouble(materdata.Price * sitem.Nums);
                //                    Instord.Num = Convert.ToDouble(sitem.Nums);
                //                    Instord.CreatorId = _operator.UserId;
                //                    Instord.CreateTime = DateTime.Now;
                //                    Instord.Deleted = false;
                //                    Instord.PackId = sitem.PackId;
                //                    Instord.OldOrNew = sitem.OldOrNew;
                //                    InStorDetail.Add(Instord);

                //                }
                //            }
                //        }

                //        //计算单个物料
                //        foreach (var item in PositiveNumber)
                //        {
                //            //获取当前物料实际盘点的数据
                //            var itemdata = data.CheckPack.Where(x => x.StorId == itemstor.StorId && x.localId == item.localId && x.MaterialId == item.MaterialId && x.PackId == "").ToList();
                //            if (itemdata.Count > 0)
                //            {
                //                var numdata = itemdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.Nums) }).FirstOrDefault();

                //                PB_StockLog log = new PB_StockLog();
                //                log.Id = IdHelper.GetId();
                //                log.PackId = "";
                //                log.MaterialId = item.MaterialId;
                //                log.StorId = item.StorId;
                //                log.LocationId = item.localId;
                //                log.StockNumber = item.DisNum;
                //                log.CreatorId = _operator.UserId;
                //                log.Deleted = false;
                //                log.CreatorName = userdata.RealName;
                //                log.OperatorId = _operator.UserId;
                //                log.Type = 1;
                //                log.CreateTime = DateTime.Now;
                //                log.State = 0;
                //                log.OldOrNew = 1;
                //                StockLog.Add(log);

                //                //入库单明细
                //                TD_InStorDetail Instord = new TD_InStorDetail();
                //                Instord.Id = IdHelper.GetId();
                //                Instord.InStorId = InId;
                //                Instord.StorId = item.StorId;
                //                Instord.LocalId = item.localId;
                //                Instord.MaterialId = item.MaterialId;
                //                Instord.Price = 0;
                //                Instord.TotalAmt = 0;
                //                Instord.Num = Convert.ToDouble(item.DisNum);
                //                Instord.CreatorId = _operator.UserId;
                //                Instord.CreateTime = DateTime.Now;
                //                Instord.Deleted = false;
                //                Instord.PackId = "";
                //                Instord.OldOrNew = 1;
                //                InStorDetail.Add(Instord);

                //            }
                //        }

                //    }
                //    #endregion

                //    //盘差值为负数
                //    #region
                //    var negative = data.CheckData.Where(x => x.StorId == itemstor.StorId && x.DisNum < 0).ToList();

                //    if (negative.Count > 0)
                //    {

                //        //List<PB_Stock> PB_Stocklist = await Db.GetIQueryable<PB_Stock>().Where(x => locaIds.Contains(x.LocationId) && materialIds.Contains(x.MaterialId) && x.PackId == "").ToListAsync();
                //        List<PB_Stock> PB_Stocklist = data.StockList;
                //        //出库单Id
                //        string outId = IdHelper.GetId();

                //        List<string> packids = new List<string>();
                //        //计算包
                //        foreach (var item in negative)
                //        {
                //            //获取当前物料实际盘点包的数据
                //            var itemdata = data.CheckPack.Where(x => x.StorId == item.StorId && x.localId == item.localId && x.MaterialId == item.MaterialId && x.PackId != "").ToList();
                //            if (itemdata.Count > 0)
                //            {
                //                //获取当前物料库存明细包的数据
                //                var LocalDetail = LocalDetaillist.Where(x => x.StorId == item.StorId && x.LocalId == item.localId && x.MaterialId == item.MaterialId && x.PackId != "").ToList();
                //                foreach (var pitem in LocalDetail)
                //                {
                //                    var pdata = itemdata.Where(x => x.PackId == pitem.PackId).FirstOrDefault();
                //                    if (pdata == null)
                //                    {
                //                        packids.Add(pitem.PackId);

                //                    }
                //                }
                //            }
                //        }

                //        //获取盘点单盘差值为负数的库存明细
                //        var locapackdata = LocalDetaillist.Where(x => x.StorId == itemstor.StorId && packids.Contains(x.PackId)).ToList();
                //        string pickids = "";///////////////////////////////////////////cn
                //        foreach (var item in locapackdata)
                //        {
                //            var materdata = Materiallist.Where(x => x.Id == item.MaterialId).FirstOrDefault();

                //            //出库单明细
                //            TD_OutStorDetail outdetail = new TD_OutStorDetail();
                //            outdetail.Id = IdHelper.GetId();
                //            outdetail.StorId = item.StorId;
                //            outdetail.OutStorId = item.StorId;
                //            outdetail.LocalId = item.LocalId;
                //            outdetail.MaterialId = item.MaterialId;
                //            outdetail.OutNum = Convert.ToDouble(item.Num);
                //            outdetail.Price = Convert.ToDouble(materdata.Price);
                //            outdetail.TotalAmt = Convert.ToDouble(materdata.Price * item.Num);
                //            outdetail.CreateTime = DateTime.Now;
                //            outdetail.CreatorId = _operator.UserId;
                //            outdetail.Deleted = false;
                //            OutStorDetail.Add(outdetail);

                //            PB_StockLog log = new PB_StockLog();
                //            log.Id = IdHelper.GetId();
                //            log.PackId = item.PackId;
                //            log.MaterialId = item.MaterialId;
                //            log.StorId = item.StorId;
                //            log.LocationId = item.LocalId;
                //            log.StockNumber = item.Num;
                //            log.CreatorId = _operator.UserId;
                //            log.Deleted = false;
                //            log.CreatorName = userdata.RealName;
                //            log.OperatorId = _operator.UserId;
                //            log.Type = 1;
                //            log.CreateTime = DateTime.Now;
                //            log.State = 1;
                //            log.OldOrNew = item.OldOrNew;
                //            StockLog.Add(log);

                //            pickids += "'" + item.PackId + "',";/////////////////////////////cn
                //            //sqlMain += @" delete from IT_LocalDetail where PackId='" + item.PackId + "'; ";
                //            //sqlMain += @" delete from PB_Stock where PackId='" + item.PackId + "'; ";
                //            //sqlMain += @" update PB_PackList set Status = 4, OutStorTime = NOW() where Id = '" + item.PackId + "'; ";

                //        }
                //        ///////////////////cn begin
                //        if (!pickids.IsNullOrEmpty())
                //        {
                //            sqlMain += @" delete from IT_LocalDetail where PackId in (" + pickids.Substring(0, pickids.Length - 1) + ");";
                //            sqlMain += @" delete from PB_Stock where PackId in (" + pickids.Substring(0, pickids.Length - 1) + ");";
                //            sqlMain += @" update PB_PackList set Status = 4, OutStorTime = NOW() where Id  in (" + pickids.Substring(0, pickids.Length - 1) + ");";
                //        }                        
                //        ///////////////////cn end
                //        //计算单个物料
                //        foreach (var item in negative)
                //        {
                //            double? disnum = -item.DisNum;
                //            var materdata = Materiallist.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                //            //出库单明细
                //            TD_OutStorDetail outdetail = new TD_OutStorDetail();
                //            outdetail.Id = IdHelper.GetId();
                //            outdetail.StorId = item.StorId;
                //            outdetail.OutStorId = outId;
                //            outdetail.LocalId = item.localId;
                //            outdetail.MaterialId = item.MaterialId;
                //            outdetail.OutNum = Convert.ToDouble(disnum);
                //            outdetail.Price = Convert.ToDouble(materdata.Price);
                //            outdetail.TotalAmt = Convert.ToDouble(materdata.Price * disnum);
                //            outdetail.CreateTime = DateTime.Now;
                //            outdetail.CreatorId = _operator.UserId;
                //            outdetail.Deleted = false;
                //            OutStorDetail.Add(outdetail);

                //            //增加出库日志
                //            PB_StockLog pblog = new PB_StockLog();
                //            pblog.Id = IdHelper.GetId();
                //            pblog.PackId = "";
                //            pblog.StorId = item.StorId;
                //            pblog.MaterialId = item.MaterialId;
                //            pblog.LocationId = item.localId;
                //            pblog.StockNumber = disnum;
                //            pblog.CreatorId = _operator.UserId;
                //            pblog.CreatorName = userdata.RealName;
                //            pblog.OperatorId = _operator.UserId;
                //            pblog.Type = 1;
                //            pblog.OrderID = "";
                //            pblog.CreateTime = DateTime.Now;
                //            pblog.State = 1;
                //            StockLog.Add(pblog);
                //        }
                //    }
                //    #endregion
                //}
                #endregion

                //增加入库单明细汇总表
                var StorDetail = InStorDetail.GroupBy(x => new { x.InStorId, x.StorId, x.LocalId, x.MaterialId, x.Price }).Select(x => new { InStorId = x.Key.InStorId, StorId = x.Key.StorId, LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(i => i.Num) }).ToList();
                foreach (var item in StorDetail)
                {
                    TD_InStorRecord InStorR = new TD_InStorRecord();
                    InStorR.Id = IdHelper.GetId();
                    InStorR.InStorId = item.InStorId;
                    InStorR.StorId = item.StorId;
                    InStorR.MaterialId = item.MaterialId;
                    InStorR.Price = item.Price;
                    InStorR.TotalAmt = item.Price * item.Nums;
                    InStorR.Num = item.Nums;
                    InStorR.CreateTime = DateTime.Now;
                    InStorR.CreatorId = _operator.UserId;
                    InStorR.Deleted = false;
                    InStorRecord.Add(InStorR);
                }

                //增加入库单主表
                var StorDetailTotal = InStorRecord.GroupBy(x => new { x.InStorId, x.StorId }).Select(x => new { InStorId = x.Key.InStorId, StorId = x.Key.StorId, TotalNums = x.Sum(i => i.Num), TotalPrice = x.Sum(i => i.TotalAmt) }).ToList();

                foreach (var item in StorDetailTotal)
                {
                    TD_InStorage indata = new TD_InStorage();
                    indata.Id = item.InStorId;
                    indata.RecId = "";
                    indata.Code = GetTimeStamp();
                    indata.InStorTime = DateTime.Now;
                    indata.InType = "OtherType";
                    indata.RefCode = data.checkId;
                    indata.Status = 0;
                    indata.Remarks = "盘点单盘盈";
                    indata.StorId = item.StorId;
                    indata.TotalNum = item.TotalNums;
                    indata.TotalAmt = item.TotalPrice;
                    indata.CreateTime = DateTime.Now;
                    indata.CreatorId = _operator.UserId;
                    indata.Deleted = false;
                    indata.QrCode = h_Warehousing + "," + item.InStorId;
                    indata.DepId = userdata.FactoryId;
                    InStorage.Add(indata);
                }

                //增加出库单明细汇总表
                var outpackdata = OutStorDetail.GroupBy(x => new { x.OutStorId, x.StorId, x.LocalId, x.MaterialId, x.Price }).Select(x => new { OutStorId = x.Key.OutStorId, StorId = x.Key.StorId, LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(i => i.OutNum) }).ToList();

                foreach (var item in outpackdata)
                {
                    TD_OutStorRecord outr = new TD_OutStorRecord();
                    outr.Id = IdHelper.GetId();
                    outr.StorId = item.StorId;
                    outr.OutStorId = item.OutStorId;
                    outr.MaterialId = item.MaterialId;
                    outr.Price = item.Price;
                    outr.TotalAmt = item.Price * item.Nums;
                    outr.OutNum = item.Nums;
                    outr.CreateTime = DateTime.Now;
                    outr.CreatorId = _operator.UserId;
                    outr.Deleted = false;
                    OutStorRecord.Add(outr);
                }

                //增加出库单主表
                var outpackdataTotal = OutStorRecord.GroupBy(x => new { x.OutStorId, x.StorId }).Select(x => new { OutStorId = x.Key.OutStorId, StorId = x.Key.StorId, TotalNums = x.Sum(i => i.OutNum), TotalPrice = x.Sum(i => i.TotalAmt) }).ToList();


                foreach (var item in outpackdataTotal)
                {
                    TD_OutStorage outdata = new TD_OutStorage();
                    outdata.Id = item.OutStorId;
                    outdata.StorageId = item.StorId;
                    outdata.Code = GetTimeStamp();
                    outdata.OutTime = DateTime.Now;
                    outdata.OutType = "OtherOut";
                    outdata.RefCode = data.checkId;
                    outdata.OutNum = item.TotalNums;
                    outdata.TotalAmt = Convert.ToDouble(item.TotalPrice);
                    outdata.Status = 0;
                    outdata.Remarks = "盘点单盘亏";
                    outdata.CreateTime = DateTime.Now;
                    outdata.CreatorId = _operator.UserId;
                    outdata.Deleted = false;
                    outdata.DepId = userdata.DepartmentId;
                    outdata.ProjectId = "";
                    outdata.DesignId = "";
                    outdata.FactoryId = userdata.FactoryId;
                    outdata.QrCode = h_OutStorage + "," + item.OutStorId;
                    OutStorage.Add(outdata);
                    //                    string QrCode = h_OutStorage + "," + item.OutStorId;
                    //                    outsql += @" insert into TD_OutStorage (Id,StorageId,`Code`,OutTime,OutType,RefCode,OutNum,TotalAmt,`Status`,Remarks,CreateTime,CreatorId,Deleted,DepId,ProjectId,DesignId,FactoryId,QrCode) values
                    //('" + item.OutStorId + "','" + item.StorId + "','"+ GetTimeStamp() + "',NOW(),'OtherOut','"+ data.checkId + "','"+ item.TotalNums + "','"+ Convert.ToDouble(item.TotalPrice) + "',0,'盘点单盘亏',NOW(),'"+ _operator.UserId + "',0,'"+ userdata.DepartmentId + "','','','"+ userdata.FactoryId + "','"+ QrCode + "'); ";
                }
                //把实际盘点的数据分组求和，修改库存汇总表数据
                //var packdata = data.CheckPack.GroupBy(x => new { x.MaterialId, x.StorId, x.localId, x.OldOrNew }).Select(x => new { MaterialId = x.Key.MaterialId, StorId = x.Key.StorId, localId = x.Key.localId, OldOrNew = x.Key.OldOrNew, Nums = x.Sum(i => i.Nums) }).ToList();

                //foreach (var item in LocalMaterial)
                //{
                //    //double? nums_r = 0;
                //    //var itemdatar = packdata.Where(x => x.StorId == item.StorId && x.localId == item.LocalId && x.MaterialId == item.MaterialId && x.OldOrNew == 1).FirstOrDefault();
                //    //if (itemdatar != null)
                //    //{
                //    //    nums_r = itemdatar.Nums;
                //    //}
                //    //double? nums_o = 0;
                //    //var itemdatao = packdata.Where(x => x.StorId == item.StorId && x.localId == item.LocalId && x.MaterialId == item.MaterialId && x.OldOrNew == 0).FirstOrDefault();
                //    //if (itemdatao != null)
                //    //{
                //    //    nums_o = itemdatao.Nums;
                //    //}
                //    //double? dnums = nums_r + nums_o;
                //    //sqlMain += @" update IT_LocalMaterial set Nums_N=" + nums_r + ",Nums_O=" + nums_o + ",ScanNum=(" + dnums + ") where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocalId + "'; ";

                //    //入库的
                //    var indata = InStorDetail.Where(x => x.MaterialId == item.MaterialId && x.StorId == item.StorId && x.LocalId == item.LocalId).GroupBy(x => new { x.MaterialId, x.StorId, x.LocalId, x.OldOrNew }).Select(x => new { MaterialId = x.Key.MaterialId, StorId = x.Key.StorId, LocalId = x.Key.LocalId, OldOrNew = x.Key.OldOrNew, Nums = x.Sum(i => i.Num) }).ToList();
                //    if (indata.Count > 0)
                //    {
                //        double? nums_r = 0;
                //        var itemdatar = indata.Where(x => x.StorId == item.StorId && x.LocalId == item.LocalId && x.MaterialId == item.MaterialId && x.OldOrNew == 1).FirstOrDefault();
                //        if (itemdatar != null)
                //        {
                //            nums_r = itemdatar.Nums;
                //        }
                //        double? nums_o = 0;
                //        var itemdatao = indata.Where(x => x.StorId == item.StorId && x.LocalId == item.LocalId && x.MaterialId == item.MaterialId && x.OldOrNew == 0).FirstOrDefault();
                //        if (itemdatao != null)
                //        {
                //            nums_o = itemdatao.Nums;
                //        }
                //        double? dnums = nums_r + nums_o;
                //        data.SqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + nums_r + ",Nums_O=IFNULL(Nums_O,0)+" + nums_o + ",ScanNum=IFNULL(ScanNum,0)+(" + dnums + ") where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocalId + "'; ";
                //    }

                //    //出库的
                //    var outdata = OutStorDetail.Where(x => x.MaterialId == item.MaterialId && x.StorId == item.StorId && x.LocalId == item.LocalId).GroupBy(x => new { x.MaterialId, x.StorId, x.LocalId, x.OldOrNew }).Select(x => new { MaterialId = x.Key.MaterialId, StorId = x.Key.StorId, LocalId = x.Key.LocalId, OldOrNew = x.Key.OldOrNew, Nums = x.Sum(i => i.OutNum) }).ToList();
                //    if (outdata.Count > 0)
                //    {
                //        double? nums_r = 0;
                //        var itemdatar = outdata.Where(x => x.StorId == item.StorId && x.LocalId == item.LocalId && x.MaterialId == item.MaterialId && x.OldOrNew == 1).FirstOrDefault();
                //        if (itemdatar != null)
                //        {
                //            nums_r = itemdatar.Nums;
                //        }
                //        double? nums_o = 0;
                //        var itemdatao = outdata.Where(x => x.StorId == item.StorId && x.LocalId == item.LocalId && x.MaterialId == item.MaterialId && x.OldOrNew == 0).FirstOrDefault();
                //        if (itemdatao != null)
                //        {
                //            nums_o = itemdatao.Nums;
                //        }
                //        double? dnums = nums_r + nums_o;
                //        data.SqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + nums_r + ",Nums_O=IFNULL(Nums_O,0)-" + nums_o + ",ScanNum=IFNULL(ScanNum,0)-(" + dnums + ") where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocalId + "'; ";
                //    }

                //}


                Db.Insert<IT_LocalDetail>(data.itdata);
                Db.Insert<PB_Stock>(data.StockList);
                Db.Insert<PB_StockLog>(data.StockLog);
                Db.Insert<TD_InStorDetail>(InStorDetail);
                Db.Insert<TD_InStorRecord>(InStorRecord);
                Db.Insert<TD_InStorage>(InStorage);
                Db.Insert<TD_OutStorDetail>(OutStorDetail);
                Db.Insert<TD_OutStorRecord>(OutStorRecord);
                Db.Insert<TD_OutStorage>(OutStorage);
                //if (!outsql.IsNullOrEmpty())
                //{
                //    await ExecuteSqlAsync(outsql);
                //}
                if (!data.SqlMain.IsNullOrEmpty())
                {
                    await ExecuteSqlAsync(data.SqlMain);
                }
            }
            //string sqlMains = @" update TD_Check set Status=4,IsComplete=1 where Id='" + data.checkId + "'; ";
            // await ExecuteSqlAsync(sqlMains);

        }

        /// <summary>
        /// 盘差完成(并矫正库存数据)
        /// </summary>
        /// <param name="CheckId">盘点单Id</param>
        /// <returns></returns>
        public async Task UpCheckDataAsync(string CheckId)
        {
            //获取盘点单对应的库存明细信息
            string sql = @" select Id,MaterialId,LocalId,Num,OldOrNew from ( select a.CheckId,b.* from TD_CheckData as a join IT_LocalDetail as b on a.LocalId=b.LocalId and a.MaterialId=b.MaterialId where CheckId='" + CheckId + "') as t group by Id,MaterialId,LocalId,Num,OldOrNew ";
            List<MaterialLocaDTO> MaterialLocaList = await Db.GetListBySqlAsync<MaterialLocaDTO>(sql);
            string sqlMain = string.Empty;
            var MaterialLoca = MaterialLocaList.GroupBy(x => new { x.MaterialId, x.LocalId, x.OldOrNew }).Select(x => new { MaterialId = x.Key.MaterialId, LocalId = x.Key.LocalId, OldOrNew = x.Key.OldOrNew, Num = x.Sum(i => i.Num) }).ToList();
            //获取盘点单明细
            List<TD_CheckData> CheckData = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == CheckId).ToListAsync();
            foreach (var item in CheckData)
            {
                //获取新
                var item_N = MaterialLoca.Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.localId && x.OldOrNew == 1).FirstOrDefault();
                double? Nums_N = item_N == null ? 0 : item_N.Num;
                //获取旧
                var item_O = MaterialLoca.Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.localId && x.OldOrNew == 0).FirstOrDefault();
                double? Nums_O = item_O == null ? 0 : item_O.Num;
                double? scanums = Nums_N + Nums_O;
                sqlMain += @" update IT_LocalMaterial set Nums_N=" + Nums_N + ",Nums_O=" + Nums_O + ",ScanNum=" + scanums + " where MaterialId='" + item.MaterialId + "' and LocalId='" + item.localId + "'; ";
            }
            //修改盘点单状态为已完成
            sqlMain += @" update TD_Check set Status=4,IsComplete=1 where Id='" + CheckId + "'; ";
            await ExecuteSqlAsync(sqlMain);
        }


        #region  判断是否能进行入库和出库操作
        /// <summary>
        /// 判断当时公司下是否有盘点单
        /// 盘点单是否在开始作业
        /// 是（true）
        /// 否（false）
        /// </summary>
        /// <param name="MaterialId">物料id</param>
        /// <param name="StorId">仓库id</param>
        /// <param name="LocalId">仓库id</param>
        /// <returns></returns>

        public async Task<CheckBool> GetTrueOrFalse(string MaterialId, string StorId, string LocalId)
        {
            CheckBool checkbl = new CheckBool();
            //通过物料id和仓库id获取盘点单是否在盘点中
            Expression<Func<TD_Check, TD_CheckData, InventoryLockCheckDTO>> select = (a, b) => new InventoryLockCheckDTO
            {
                Status = a.Status,
                MaterialStorId = b.StorId,
                MaterialId = b.MaterialId,
                MaterialLocalId = b.localId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<TD_Check>().AsExpandable()
                    join b in Db.GetIQueryable<TD_CheckData>() on a.Id equals b.CheckId into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            InventoryLockCheckDTO checkdata = await q.Where(x => x.MaterialId == MaterialId && x.MaterialStorId == StorId && x.MaterialLocalId == LocalId && x.Status >= 2 && x.Status < 4).FirstOrDefaultAsync();
            if (checkdata != null)
            {
                checkbl.boolType = false;
            }
            else
            {
                checkbl.boolType = true;
            }
            return checkbl;
        }




        #endregion


        /// <summary>
        /// PDA盘点
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task InsertCheckDataAsync(CheckData data)
        {
            //获取包Id
            string packId = string.Empty;
            string materialId = string.Empty;
            string jobid = string.Empty;
            string packmodel = data.PackQrCode.Split(',')?[0].ToString();
            Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");

            if (packmodel == "13")
            {
                packId = data.PackQrCode.Split(',')?[1].ToString();
            }
            else if (packmodel == "04")
            {
                var model = data.PackQrCode.Split(',');
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描正确的二维码信息");
                    }
                    else
                    {
                        materialId = model?[3].ToString();
                    }
                }
                else
                {
                    materialId = model?[1].ToString();
                }
                //合并重复物料指向新的物料Id
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (!materdata.TransferId.IsNullOrEmpty())
                {
                    materialId = materdata.TransferId;
                }
            }
            else if (packmodel == "14")
            {
                jobid = data.PackQrCode.Split(',')?[1].ToString();
                //查询单个成品是否绑定包信息
                //PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                //if (jobdata != null)
                //{
                //    if (!jobdata.PackId.IsNullOrEmpty())
                //    {
                //        packmodel = "13";
                //        packId = jobdata.PackId;
                //    }
                //}
            }
            //货位Id
            string locaId = data.LocaQrCode.Split(',')?[1].ToString();
            //盘点单Id
            string checkId = data.CheckQrCode.Split(',')?[1].ToString();

            PB_Location locatdata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == locaId).FirstOrDefaultAsync();

            TD_Check checkd = await Db.GetIQueryable<TD_Check>().Where(x => x.Id == checkId).FirstOrDefaultAsync();
            if (checkd != null)
            {
                if (checkd.Status >= 3)
                {
                    throw new BusException("盘点单已提交");
                }
            }

            //包
            if (packmodel == "13")
            {

                //查看包的信息
                PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
                if (packdata == null)
                {
                    throw new BusException("请检查包是否存在");
                }
                //IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).FirstOrDefaultAsync();
                //if (LocalDetail != null)
                //{
                //    if (LocalDetail.LocalId != locaId)
                //    {
                //        View_StorAreaRackLocation locadata = await Db.GetIQueryable<View_StorAreaRackLocation>().Where(x => x.Id == LocalDetail.LocalId).FirstOrDefaultAsync();
                //        throw new BusException("此包在" + locadata.StorAreaName + "货位上");
                //    }
                //}
                //查询包是否盘点过
                List<TD_CheckPack> listdata = await Db.GetIQueryable<TD_CheckPack>().Where(x => x.CheckId == checkId && x.PackId == packId).ToListAsync();
                if (listdata.Count > 0)
                {
                    throw new BusException("包已盘点,不能重复扫描");
                }
                //标准包
                if (packdata.PackageType == 0)
                {
                    //根据包的信息对比盘点单明细是否对应
                    //TD_CheckData checkdata = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == checkId && x.StorId == locatdata.StorId && x.localId == locaId && x.MaterialId == packdata.MaterialId).FirstOrDefaultAsync();
                    //if (checkdata != null)
                    //{
                        //盘点实时表
                        TD_CheckPack CheckPackdata = new TD_CheckPack();
                        CheckPackdata.Id = IdHelper.GetId();
                        CheckPackdata.CheckId = checkId;
                        CheckPackdata.StorId = locatdata.StorId;
                        CheckPackdata.localId = locaId;
                        CheckPackdata.MaterialId = packdata.MaterialId;
                        CheckPackdata.PackId = packId;
                        CheckPackdata.Nums = packdata.Nums;
                        CheckPackdata.CreatorId = _operator.UserId;
                        CheckPackdata.CreateTime = DateTime.Now;
                        CheckPackdata.OldOrNew = packdata.OldOrNew;
                        CheckPackdata.JobId = "";
                        await Db.InsertAsync<TD_CheckPack>(CheckPackdata);
                    //}
                    //else
                    //{
                    //    throw new BusException("请检查包下的物料是否在盘点物料内");
                    //}
                }
                //混合包
                else if (packdata.PackageType == 1)
                {
                    List<PB_JobBookingQrCode> PackList = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId).ToListAsync();
                    var packnum = PackList.GroupBy(x => new { x.PackId, x.MaterialId }).Select(x => new { PackId = x.Key.PackId, MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                    List<string> materiallist = new List<string>();
                    foreach (var item in packnum)
                    {
                        materiallist.Add(item.MaterialId);
                    }
                    //根据包的信息对比盘点单明细是否对应
                    //List<TD_CheckData> CheckDatalist = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == checkId && x.StorId == locatdata.StorId && x.localId == locaId && materiallist.Contains(x.MaterialId)).ToListAsync();
                    //if (CheckDatalist.Count > 0)
                    //{
                        List<TD_CheckPack> Checklist = new List<TD_CheckPack>();
                        //string sqlMain = string.Empty;
                        foreach (var item in packnum)
                        {
                            TD_CheckPack checkdata = new TD_CheckPack();
                            checkdata.Id = IdHelper.GetId();
                            checkdata.CheckId = checkId;
                            checkdata.StorId = locatdata.StorId;
                            checkdata.localId = locaId;
                            checkdata.MaterialId = item.MaterialId;
                            checkdata.PackId = packId;
                            checkdata.Nums = item.Nums;
                            checkdata.CreatorId = _operator.UserId;
                            checkdata.CreateTime = DateTime.Now;
                            checkdata.OldOrNew = packdata.OldOrNew;
                            checkdata.JobId = "";
                            Checklist.Add(checkdata);
                        }
                        await Db.InsertAsync<TD_CheckPack>(Checklist);
                    //}
                    //else
                    //{
                    //    throw new BusException("请检查包下的物料是否在盘点物料内");
                    //}
                }
            }
            //单个物料
            else if (packmodel == "04")
            {
                //根据物料的信息对比盘点单明细是否对应
                //TD_CheckData CheckData = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == checkId && x.StorId == locatdata.StorId && x.localId == locaId && x.MaterialId == materialId).FirstOrDefaultAsync();
                //if (CheckData != null)
                //{
                    TD_CheckPack checkdata = new TD_CheckPack();
                    checkdata.Id = IdHelper.GetId();
                    checkdata.CheckId = checkId;
                    checkdata.StorId = locatdata.StorId;
                    checkdata.localId = locaId;
                    checkdata.MaterialId = materialId;
                    checkdata.PackId = "";
                    checkdata.Nums = data.Nums;
                    checkdata.CreatorId = _operator.UserId;
                    checkdata.CreateTime = DateTime.Now;
                    checkdata.OldOrNew = 1;
                    checkdata.JobId = "";
                    await Db.InsertAsync<TD_CheckPack>(checkdata);
                //}
                //else
                //{
                //    throw new BusException("请检查物料是否在盘点物料内");
                //}
            }
            //单个成品
            else if (packmodel == "14")
            {
                if (linktypedata.Whether == true)
                {
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                    if (jobdata == null)
                    {
                        throw new BusException("请检查成品是否存在");
                    }
                    if (!jobdata.PackId.IsNullOrEmpty())
                    {
                        throw new BusException("请扫描不在包内的成品");
                    }
                    //根据物料的信息对比盘点单明细是否对应
                    //TD_CheckData CheckData = await Db.GetIQueryable<TD_CheckData>().Where(x => x.CheckId == checkId && x.StorId == locatdata.StorId && x.localId == locaId && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                    //if (CheckData != null)
                    //{
                    TD_CheckPack CheckPack = await Db.GetIQueryable<TD_CheckPack>().Where(x => x.CheckId == checkId && x.JobId == jobid).FirstOrDefaultAsync();
                    if (CheckPack != null)
                    {
                        throw new BusException("请勿重复扫描");
                    }
                    TD_CheckPack checkdata = new TD_CheckPack();
                    checkdata.Id = IdHelper.GetId();
                    checkdata.CheckId = checkId;
                    checkdata.StorId = locatdata.StorId;
                    checkdata.localId = locaId;
                    checkdata.MaterialId = jobdata.MaterialId;
                    checkdata.PackId = "";
                    checkdata.Nums = 1;
                    checkdata.CreatorId = _operator.UserId;
                    checkdata.CreateTime = DateTime.Now;
                    checkdata.OldOrNew = 1;
                    checkdata.JobId = jobid;
                    await Db.InsertAsync<TD_CheckPack>(checkdata);
                    //}
                    //else
                    //{
                    //    throw new BusException("请检查物料是否在盘点物料内");
                    //}
                }
                else
                {
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();

                    TD_CheckPack checkdata = new TD_CheckPack();
                    checkdata.Id = IdHelper.GetId();
                    checkdata.CheckId = checkId;
                    checkdata.StorId = locatdata.StorId;
                    checkdata.localId = locaId;
                    checkdata.MaterialId = jobdata.MaterialId;
                    checkdata.PackId = "";
                    checkdata.Nums = data.Nums;
                    checkdata.CreatorId = _operator.UserId;
                    checkdata.CreateTime = DateTime.Now;
                    checkdata.OldOrNew = 1;
                    checkdata.JobId = "";
                    await Db.InsertAsync<TD_CheckPack>(checkdata);
                }
            }
        }

        /// <summary>
        /// PDA盘点获取包信息
        /// </summary>
        /// <param name="PackQrCode">包二维码</param>
        /// <returns></returns>
        public async Task<CheckPackMaterialDetailDTO> GetCheckPackMaterialDetailDataAsync(string PackQrCode)
        {
            //包Id
            string packid = PackQrCode.Split(',')?[1].ToString();
            PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
            if (packdata != null)
            {
                string sqlMain = @" select a.PackId,a.MaterialId,b.`Name` as MaterialName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,b.ProductCode,a.Nums from PB_PackMaterialCount as a left join PB_Material as b on a.MaterialId=b.Id where a.PackId='" + packid + "' ";

                List<CheckPackMaterialDataDTO> StockUpPackDetail = await Db.GetListBySqlAsync<CheckPackMaterialDataDTO>(sqlMain);
                CheckPackMaterialDetailDTO supack = new CheckPackMaterialDetailDTO();
                supack.PackId = packdata.Id;
                supack.PackQrCode = packdata.QrCode;
                supack.BoxName = packdata.BoxName;
                supack.Nums = packdata.Nums;
                supack.CheckPackMaterial = StockUpPackDetail;
                return supack;
            }
            else
            {
                throw new BusException("请扫描正确的包");
            }
        }

        /// <summary>
        /// PDA盘点扫描成品码输入数量
        /// </summary>
        /// <param name="JobQrCode">成品二维码</param>
        /// <param name="LocaQrCode">货位二维码</param>
        /// <returns></returns>
        public async Task<object> GetCheckJobMaterialDataAsync(string JobQrCode, string LocaQrCode)
        {
            //成品Id
            string jobid = JobQrCode.Split(',')?[1].ToString();
            //货位Id
            string localid = LocaQrCode.Split(',')?[1].ToString();

            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
            if (jobdata != null)
            {
                if (jobdata.PackId.IsNullOrEmpty())
                {
                    //获取物料信息
                    PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                    CheckJobMaterialDTO jobmaterial = new CheckJobMaterialDTO();
                    jobmaterial.MaterialId = jobdata.MaterialId;
                    jobmaterial.MaterialCode = Material.Code;
                    jobmaterial.MaterialName = Material.Name;
                    jobmaterial.MaterialSpec = Material.Spec;
                    jobmaterial.PackQrCode = h_FinishedProduct + "," + jobid;
                    jobmaterial.PackId = "";
                    jobmaterial.Nums = 1;
                    return jobmaterial;
                }
                else
                {
                    string packid = jobdata.PackId;
                    PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
                    string sqlMain = @" select a.PackId,a.MaterialId,b.`Name` as MaterialName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,b.ProductCode,a.Nums from PB_PackMaterialCount as a left join PB_Material as b on a.MaterialId=b.Id where a.PackId='" + packid + "' ";

                    List<CheckPackMaterialDataDTO> StockUpPackDetail = await Db.GetListBySqlAsync<CheckPackMaterialDataDTO>(sqlMain);
                    CheckPackMaterialDetailDTO supack = new CheckPackMaterialDetailDTO();
                    supack.PackId = packdata.Id;
                    supack.PackQrCode = packdata.QrCode;
                    supack.BoxName = packdata.BoxName;
                    supack.Nums = packdata.Nums;
                    supack.CheckPackMaterial = StockUpPackDetail;
                    return supack;
                }
            }
            else
            {
                throw new BusException("请检查成品码是否存在");
            }

        }

        /// <summary>
        /// PDA盘点扫描单个物料
        /// </summary>
        /// <param name="PackQrCode">物料二维码</param>
        /// <param name="LocaQrCode">货位二维码</param>
        /// <returns></returns>
        public async Task<CheckMaterialDTO> GetCheckMaterialAsync(string PackQrCode, string LocaQrCode)
        {
            var packmodel = PackQrCode.Split(',')?[0];
            string packid = string.Empty;
            if (packmodel == "04")
            {
                var model = PackQrCode.Split(',');
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描或输入正确的物料二维码");
                    }
                    else
                    {
                        packid = model?[3].ToString();
                    }
                }
                else
                {
                    packid = model?[1].ToString();
                }
            }
            //货位Id
            string locaId = LocaQrCode.Split(',')?[1].ToString();
            //合并重复物料指向新的物料Id
            PB_Material mater = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == packid).FirstOrDefaultAsync();
            if (!mater.TransferId.IsNullOrEmpty())
            {
                packid = mater.TransferId;
            }
            //IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.LocalId == locaId && x.MaterialId == packid && x.PackId == "").FirstOrDefaultAsync();
            //if (LocalDetail == null)
            //{
            //    throw new BusException("请扫描相同货位的物料");
            //}
            PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == packid).FirstOrDefaultAsync();
            if (materdata != null)
            {
                CheckMaterialDTO data = new CheckMaterialDTO();
                data.Code = materdata.Code;
                data.Name = materdata.Name;
                data.Spec = materdata.Spec;
                return data;
            }
            else
            {
                throw new BusException("请检查物料是否存在");
            }
        }

        /// <summary>
        /// PDA盘点扫描单个物料
        /// </summary>
        /// <param name="CheckQrCode">物料二维码</param>
        /// <param name="LocaQrCode">货位二维码</param>
        /// <returns></returns>
        public async Task<PB_Location> GetCheckLocationAsync(string CheckQrCode, string LocaQrCode)
        {
            //盘点单Id
            string checkId = CheckQrCode.Split(',')?[1].ToString();
            //货位Id
            string locaId = LocaQrCode.Split(',')?[1].ToString();
            TD_CheckLoca CheckLoca = await Db.GetIQueryable<TD_CheckLoca>().Where(x => x.CheckId == checkId && x.StorLocaId == locaId).FirstOrDefaultAsync();
            if (CheckLoca.IsNullOrEmpty())
            {
                throw new BusException("请扫描盘点单对应的货位");
            }
            PB_Location Location = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == locaId).FirstOrDefaultAsync();
            var areadata = await Db.GetIQueryable<PB_StorArea>().Where(x => x.Id == Location.AreaId).FirstOrDefaultAsync();
            var rackdata = await Db.GetIQueryable<PB_Rack>().Where(x => x.Id == Location.RackId).FirstOrDefaultAsync();
            Location.Name = areadata.Name + "/" + rackdata.Name + "/" + Location.Name;
            return Location;
        }

        /// <summary>
        /// PDA盘点列表
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<Check> GetCheckDetailListAsync(PageCheckData data)
        {
            Check cdata = new Check();
            string checkId = data.CheckQrCode.Split(',')?[1].ToString();
            int index = (data.pageIndex - 1) * data.pageRows + 1;
            string sql = @"select * from ( 
select *, ROW_NUMBER()over(order by CreateTime desc) as Rnumber from ( 
select  '' as Id,a.CheckId,a.PackId,a.MaterialId,b.BoxName,c.`Code` as MaterialCode,c.Spec as MaterialSpec,CONCAT(e.`Name`,'/',f.`Name`,'/',d.`Name`) as LocalName,a.Nums,a.CreatorId,a.CreateTime,a.JobId from TD_CheckPack as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id join PB_Location as d on a.localId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.CheckId='{0}' and b.PackageType=0 
UNION ALL 
select '' as Id,CheckId,PackId,'' as MaterialId,BoxName,'' as MaterialCode,'' as MaterialSpec,LocalName,SUM(Nums) as Nums,CreatorId,CreateTime,'' as JobId from ( 
select a.CheckId,a.PackId,a.MaterialId,b.BoxName,c.`Code` as MaterialCode,c.Spec as MaterialSpec,CONCAT(e.`Name`,'/',f.`Name`,'/',d.`Name`) as LocalName,a.Nums,a.CreatorId,DATE_FORMAT(a.CreateTime,'%Y-%m-%d %H:%i:00') as CreateTime from TD_CheckPack as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id join PB_Location as d on a.localId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.CheckId='{0}' and b.PackageType=1 ) as t group by CheckId,PackId,BoxName,LocalName,CreatorId,CreateTime 
UNION ALL 
select a.Id,a.CheckId,a.PackId,a.MaterialId,b.`Name` as BoxName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,a.Nums,a.CreatorId,a.CreateTime,a.JobId  from TD_CheckPack as a join PB_Material as b on a.MaterialId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id where a.CheckId='{0}' and a.PackId='' and a.JobId=''
UNION ALL 
select a.Id,a.CheckId,a.PackId,a.MaterialId,b.`Name` as BoxName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,a.Nums,a.CreatorId,a.CreateTime,a.JobId  from TD_CheckPack as a join PB_Material as b on a.MaterialId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id where a.CheckId='{0}' and a.PackId='' and a.JobId!=''
) as tt 
) as tb where  Rnumber between " + index + " and (" + data.pageIndex * data.pageRows + ") ";
            string sqlMain = string.Format(sql, checkId);
            List<CheckDetailDTO> listdata = await Db.GetListBySqlAsync<CheckDetailDTO>(sqlMain);
            List<TD_CheckPack> CheckPack = await Db.GetIQueryable<TD_CheckPack>().Where(x => x.CheckId == checkId).ToListAsync();
            var CheckPackNums = CheckPack.GroupBy(x => new { x.CheckId }).Select(x => new { CheckId = x.Key.CheckId, Nums = x.Sum(i => i.Nums) }).FirstOrDefault();
            cdata.TotalNums = Convert.ToInt32(CheckPackNums == null ? 0 : CheckPackNums.Nums);
            if (listdata.Count > 0)
            {
                cdata.CheckDetail = listdata;
            }
            else
            {
                cdata.CheckDetail = new List<CheckDetailDTO>();
            }
            return cdata;
        }

        /// <summary>
        /// PDA盘点单列表移除
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task DeleteCheckPackDataAsync(CheckDetailDTO data)
        {
            if (!data.PackId.IsNullOrEmpty())
            {
                string sqlMain = @" delete from TD_CheckPack where CheckId='" + data.CheckId + "' and PackId='" + data.PackId + "' ";
                await ExecuteSqlAsync(sqlMain);
            }
            else
            {
                string sqlMain = @" delete from TD_CheckPack where Id='" + data.Id + "' ";
                await ExecuteSqlAsync(sqlMain);
            }
        }


        #endregion

        #region 包重置

        /// <summary>
        /// 获取包二维码信息
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetPackQrCodeAsync()
        {
            string packId = IdHelper.GetId();
            string qrcode = h_Pack + "," + packId;
            return qrcode;
        }

        /// <summary>
        /// 获取成品对应的物料信息
        /// </summary>
        /// <param name="JobQrcode">成品二维码</param>
        /// <param name="PackStatus">false-扫描成品;true-扫描一个成品输入数量</param>
        /// <param name="PackQrCode">包二维码</param>
        /// <returns></returns>
        public async Task<PackJobMaterialDTO> GetPackJobMaterialListAsync(string JobQrcode, Boolean? PackStatus, string PackQrCode)
        {
            //成品Id
            string jobid = JobQrcode.Split(',')?[1].ToString();
            //包Id
            string packId = PackQrCode.Split(',')?[1].ToString();

            Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");
            if (linktypedata.Whether == false)
            {
                Expression<Func<PB_JobBookingQrCode, PB_Material, PackJobMaterialDTO>> select = (a, b) => new PackJobMaterialDTO
                {
                    Id = a.Id,
                    MaterialId = a.MaterialId,
                    MaterialName = b.Name,
                    MaterialCode = b.Code,
                    MaterialSpec = b.Spec,
                    PackId = a.PackId,
                    Nums = 0
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                var data = await q.Where(x => x.Id == jobid && x.PackId == packId).FirstOrDefaultAsync();
                if (data != null)
                {
                    return data;
                }
                else
                {
                    throw new BusException("请检查成品码是否存在");
                }
            }
            else
            {
                Expression<Func<PB_JobBookingQrCode, PB_Material, PackJobMaterialDTO>> select = (a, b) => new PackJobMaterialDTO
                {
                    Id = a.Id,
                    MaterialId = a.MaterialId,
                    MaterialName = b.Name,
                    MaterialCode = b.Code,
                    MaterialSpec = b.Spec,
                    PackId = a.PackId,
                    Nums = 1
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                var data = await q.Where(x => x.Id == jobid && x.PackId == packId).FirstOrDefaultAsync();
                if (data != null)
                {
                    return data;
                }
                else
                {
                    PB_JobBookingQrCode JobBookingQrCode = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                    if (JobBookingQrCode != null)
                    {
                        PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == JobBookingQrCode.MaterialId).FirstOrDefaultAsync();
                        PackJobMaterialDTO PackJobMaterial = new PackJobMaterialDTO();
                        PackJobMaterial.Id = jobid;
                        PackJobMaterial.MaterialId = Material.Id;
                        PackJobMaterial.MaterialName = Material.Name;
                        PackJobMaterial.MaterialCode = Material.Name;
                        PackJobMaterial.MaterialSpec = Material.Spec;
                        PackJobMaterial.PackId = packId;
                        PackJobMaterial.Nums = 1;
                        return PackJobMaterial;
                    }
                    else
                    {
                        throw new BusException("请检查成品码是否存在");
                    }
                }
            }
        }

        /// <summary>
        /// 包重置保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task SavePackJobDataAsync(PackJobDetailDTO data)
        {
            //包Id
            string packId = data.PackQrCode.Split(',')?[1].ToString();

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            string sqlMain = string.Empty;

            Base_LinkType lingtypedata = await _opdept.GetLinkType("MaterialCode");

            if (lingtypedata.Whether == false)
            {
                //获取包下的所有成品信息
                List<PB_JobBookingQrCode> joblist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId).ToListAsync();
                //List<string> jobids = new List<string>();
                double? dnums = 0;
                foreach (var item in data.PackJobMaterial)
                {
                    dnums += item.Nums;
                }
                //修改成品与包的关系
                //sqlMain += @" update PB_JobBookingQrCode set PackStatus=0 where Id in ('" + string.Join("','", jobids.ToArray()) + "'); ";
                //修改包的包装数量
                sqlMain += @" update PB_PackList set Nums='" + dnums + "' where Id='" + packId + "'; ";

                //查询库存明细包的信息
                List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();
                List<TD_OutStorDetail> OutStorDetail = new List<TD_OutStorDetail>();
                List<TD_OutStorRecord> OutStorRecord = new List<TD_OutStorRecord>();
                List<TD_OutStorage> OutStorage = new List<TD_OutStorage>();
                List<TD_InStorDetail> InStorDetail = new List<TD_InStorDetail>();
                List<TD_InStorRecord> InStorRecord = new List<TD_InStorRecord>();
                List<TD_InStorage> InStorage = new List<TD_InStorage>();
                List<PB_StockLog> StockLog = new List<PB_StockLog>();
                string outid = IdHelper.GetId();
                double? itemnums = 0;
                foreach (var item in LocalDetail)
                {
                    var itemdata = data.PackJobMaterial.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                    if (itemdata != null)
                    {
                        //修改包的包装数量
                        sqlMain += @" update PB_PackMaterialCount set Nums=" + itemdata.Nums + " where PackId='" + packId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                        sqlMain += @" update IT_LocalDetail set Num=" + itemdata.Nums + " where Id='" + item.Id + "'; ";
                        if (itemdata.Nums > item.Num)
                        {
                            itemnums = itemdata.Nums - item.Num;
                            if (item.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + itemnums + ",ScanNum=IFNULL(ScanNum,0)+" + itemnums + "  where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocalId + "'; ";
                            }
                            else if (item.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + itemnums + ",ScanNum=IFNULL(ScanNum,0)+" + itemnums + "  where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocalId + "'; ";
                            }
                            TD_InStorDetail indetail = new TD_InStorDetail();
                            indetail.Id = IdHelper.GetId();
                            indetail.InStorId = outid;
                            indetail.StorId = item.StorId;
                            indetail.LocalId = item.LocalId;
                            indetail.MaterialId = item.MaterialId;
                            indetail.Price = Convert.ToDouble(item.Price);
                            indetail.TotalAmt = Convert.ToDouble(item.Price * itemnums);
                            indetail.Num = Convert.ToDouble(itemnums);
                            indetail.CreateTime = DateTime.Now;
                            indetail.CreatorId = _operator.UserId;
                            indetail.Deleted = false;
                            indetail.PackId = packId;
                            indetail.OldOrNew = item.OldOrNew;
                            indetail.JobId = "";
                            InStorDetail.Add(indetail);

                            PB_StockLog slog = new PB_StockLog();
                            slog.Id = IdHelper.GetId();
                            slog.PackId = packId;
                            slog.MaterialId = item.MaterialId;
                            slog.StorId = item.StorId;
                            slog.LocationId = item.LocalId;
                            slog.StockNumber = itemnums;
                            slog.CreatorId = _operator.UserId;
                            slog.Deleted = false;
                            slog.CreatorName = userdata.RealName;
                            slog.Type = 1;
                            slog.CreateTime = DateTime.Now;
                            slog.State = 0;
                            slog.OldOrNew = item.OldOrNew;
                            slog.CirBillId = "";
                            slog.JobId = "";
                            StockLog.Add(slog);
                        }
                        else if (itemdata.Nums < item.Num)
                        {
                            itemnums = item.Num - itemdata.Nums;
                            if (item.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + itemnums + ",ScanNum=IFNULL(ScanNum,0)-" + itemnums + "  where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocalId + "'; ";
                            }
                            else if (item.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + itemnums + ",ScanNum=IFNULL(ScanNum,0)-" + itemnums + "  where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocalId + "'; ";
                            }
                            TD_OutStorDetail outdetail = new TD_OutStorDetail();
                            outdetail.Id = IdHelper.GetId();
                            outdetail.StorId = item.StorId;
                            outdetail.OutStorId = outid;
                            outdetail.LocalId = item.LocalId;
                            outdetail.MaterialId = item.MaterialId;
                            outdetail.Price = Convert.ToDouble(item.Price);
                            outdetail.TotalAmt = Convert.ToDouble(item.Price * itemnums);
                            outdetail.LocalNum = 0;
                            outdetail.OutNum = Convert.ToDouble(itemnums);
                            outdetail.CreateTime = DateTime.Now;
                            outdetail.CreatorId = _operator.UserId;
                            outdetail.Deleted = false;
                            outdetail.OldOrNew = item.OldOrNew;
                            OutStorDetail.Add(outdetail);

                            PB_StockLog slog = new PB_StockLog();
                            slog.Id = IdHelper.GetId();
                            slog.PackId = packId;
                            slog.MaterialId = item.MaterialId;
                            slog.StorId = item.StorId;
                            slog.LocationId = item.LocalId;
                            slog.StockNumber = itemnums;
                            slog.CreatorId = _operator.UserId;
                            slog.Deleted = false;
                            slog.CreatorName = userdata.RealName;
                            slog.Type = 1;
                            slog.CreateTime = DateTime.Now;
                            slog.State = 1;
                            slog.OldOrNew = item.OldOrNew;
                            slog.CirBillId = "";
                            slog.JobId = "";
                            StockLog.Add(slog);
                        }
                    }
                }

                double? outnum = 0;
                double? outamoun = 0;
                if (OutStorDetail.Count > 0)
                {
                    foreach (var item in OutStorDetail)
                    {
                        TD_OutStorRecord outRecord = new TD_OutStorRecord();
                        outRecord.Id = IdHelper.GetId();
                        outRecord.StorId = item.StorId;
                        outRecord.OutStorId = outid;
                        outRecord.MaterialId = item.MaterialId;
                        outRecord.Price = item.Price;
                        outRecord.TotalAmt = item.TotalAmt;
                        outRecord.OutNum = item.OutNum;
                        outRecord.CreateTime = DateTime.Now;
                        outRecord.CreatorId = _operator.UserId;
                        outRecord.Deleted = false;
                        OutStorRecord.Add(outRecord);
                        outnum += item.OutNum;
                        outamoun += item.TotalAmt;
                    }

                    TD_OutStorage outdata = new TD_OutStorage();
                    outdata.Id = outid;
                    outdata.StorageId = OutStorRecord.FirstOrDefault().StorId;
                    outdata.Code = GetTimeStamp();
                    outdata.OutTime = DateTime.Now;
                    outdata.OutType = "OtherOut";
                    outdata.RefCode = "";
                    outdata.OutNum = outnum;
                    outdata.TotalAmt = outamoun;
                    outdata.Status = 0;
                    outdata.Remarks = "包盘点(包重置)";
                    outdata.CreateTime = DateTime.Now;
                    outdata.CreatorId = _operator.UserId;
                    outdata.Deleted = false;
                    outdata.QrCode = h_OutStorage + "," + outid;
                    outdata.DepId = userdata.DepartmentId;
                    outdata.FactoryId = userdata.FactoryId;
                    OutStorage.Add(outdata);

                    await Db.InsertAsync<TD_OutStorDetail>(OutStorDetail);

                    await Db.InsertAsync<TD_OutStorRecord>(OutStorRecord);

                    await Db.InsertAsync<TD_OutStorage>(OutStorage);
                }

                if (InStorDetail.Count > 0)
                {
                    foreach (var item in InStorDetail)
                    {
                        TD_InStorRecord record = new TD_InStorRecord();
                        record.Id = IdHelper.GetId();
                        record.InStorId = outid;
                        record.StorId = item.StorId;
                        record.MaterialId = item.MaterialId;
                        record.Price = item.Price;
                        record.TotalAmt = item.TotalAmt;
                        record.Num = item.Num;
                        record.CreateTime = DateTime.Now;
                        record.CreatorId = _operator.UserId;
                        record.Deleted = false;
                        InStorRecord.Add(record);

                        outnum += item.Num;
                        outamoun += item.TotalAmt;
                    }

                    TD_InStorage Storage = new TD_InStorage();
                    Storage.Id = outid;
                    Storage.RecId = "";
                    Storage.Code = GetTimeStamp();
                    Storage.InStorTime = DateTime.Now;
                    Storage.InType = "OtherType";
                    Storage.RefCode = "";
                    Storage.Remarks = "包盘点(包重置)";
                    Storage.StorId = InStorRecord.FirstOrDefault().StorId;
                    Storage.TotalNum = Convert.ToDouble(outnum);
                    Storage.TotalAmt = Convert.ToDouble(outamoun);
                    Storage.CreateTime = DateTime.Now;
                    Storage.CreatorId = _operator.UserId;
                    Storage.Deleted = false;
                    Storage.QrCode = h_Warehousing + "," + outid;
                    Storage.DepId = userdata.DepartmentId;
                    InStorage.Add(Storage);

                    await Db.InsertAsync<TD_InStorDetail>(InStorDetail);

                    await Db.InsertAsync<TD_InStorRecord>(InStorRecord);

                    await Db.InsertAsync<TD_InStorage>(InStorage);
                }

                await Db.InsertAsync<PB_StockLog>(StockLog);

                await ExecuteSqlAsync(sqlMain);

            }
            else
            {
                //获取包在库存明细的信息
                List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();
                //查询包现在的包明细信息
                List<PB_JobBookingQrCode> JobBookingQrCode = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId).ToListAsync();
                //获取实际扫描的物料数量
                var sjmaterial = data.PackJobMaterial.GroupBy(x => new { x.MaterialId, x.PackId }).Select(x => new { MaterialId = x.Key.MaterialId, PackId = x.Key.PackId, Nums = x.Sum(i => i.Nums) }).ToList();

                List<TD_OutStorDetail> OutStorDetail = new List<TD_OutStorDetail>();
                List<TD_OutStorRecord> OutStorRecord = new List<TD_OutStorRecord>();
                List<TD_OutStorage> OutStorage = new List<TD_OutStorage>();
                List<TD_InStorDetail> InStorDetail = new List<TD_InStorDetail>();
                List<TD_InStorRecord> InStorRecord = new List<TD_InStorRecord>();
                List<TD_InStorage> InStorage = new List<TD_InStorage>();
                List<PB_StockLog> StockLog = new List<PB_StockLog>();

                List<string> jobids = new List<string>();
                double? itemnums = 0;
                string outid = IdHelper.GetId();
                //循环比较
                foreach (var item in sjmaterial)
                {
                    //查询库存物料信息
                    var itemdata = LocalDetail.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                    if (itemdata != null)
                    {
                        //实际数量比库存数量大
                        if (item.Nums > itemdata.Num)
                        {
                            //获取包现在的成品信息
                            var jobitemdata = JobBookingQrCode.Where(x => x.MaterialId == item.MaterialId).ToList();
                            //获取实际扫描的成品信息
                            var sjitemdata = data.PackJobMaterial.Where(x => x.MaterialId == item.MaterialId).ToList();
                            foreach (var jitem in sjitemdata)
                            {
                                var jitemdata = jobitemdata.Where(x => x.Id == jitem.Id).FirstOrDefault();
                                if (jitemdata == null)
                                {
                                    jobids.Add(jitem.Id);
                                }
                            }
                            sqlMain += @" update PB_JobBookingQrCode set PackId='" + packId + "' where Id in ('" + string.Join("','", jobids.ToArray()) + "'); ";
                            sqlMain += @" update PB_PackListInfo set PackId='" + packId + "' where JobBookingId in ('" + string.Join("','", jobids.ToArray()) + "');  ";
                            sqlMain += @" update PB_PackMaterialCount set Nums=" + item.Nums + " where PackId='" + packId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                            sqlMain += @" update IT_LocalDetail set Num=" + item.Nums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                            itemnums = item.Nums - itemdata.Num;
                            if (itemdata.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + itemnums + ",ScanNum=IFNULL(ScanNum,0)+" + itemnums + "  where MaterialId='" + itemdata.MaterialId + "' and LocalId='" + itemdata.LocalId + "'; ";
                            }
                            else if (itemdata.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + itemnums + ",ScanNum=IFNULL(ScanNum,0)+" + itemnums + "  where MaterialId='" + itemdata.MaterialId + "' and LocalId='" + itemdata.LocalId + "'; ";
                            }

                            foreach (var jobitem in jobids)
                            {
                                TD_InStorDetail indetail = new TD_InStorDetail();
                                indetail.Id = IdHelper.GetId();
                                indetail.InStorId = outid;
                                indetail.StorId = itemdata.StorId;
                                indetail.LocalId = itemdata.LocalId;
                                indetail.MaterialId = item.MaterialId;
                                indetail.Price = Convert.ToDouble(itemdata.Price);
                                indetail.TotalAmt = Convert.ToDouble(itemdata.Price);
                                indetail.Num = 1;
                                indetail.CreateTime = DateTime.Now;
                                indetail.CreatorId = _operator.UserId;
                                indetail.Deleted = false;
                                indetail.PackId = packId;
                                indetail.OldOrNew = itemdata.OldOrNew;
                                indetail.JobId = jobitem;
                                InStorDetail.Add(indetail);

                                PB_StockLog slog = new PB_StockLog();
                                slog.Id = IdHelper.GetId();
                                slog.PackId = packId;
                                slog.MaterialId = item.MaterialId;
                                slog.StorId = itemdata.StorId;
                                slog.LocationId = itemdata.LocalId;
                                slog.StockNumber = 1;
                                slog.CreatorId = _operator.UserId;
                                slog.Deleted = false;
                                slog.CreatorName = userdata.RealName;
                                slog.Type = 1;
                                slog.CreateTime = DateTime.Now;
                                slog.State = 0;
                                slog.OldOrNew = itemdata.OldOrNew;
                                slog.CirBillId = "";
                                slog.JobId = jobitem;
                                StockLog.Add(slog);
                            }
                        }
                        else if (item.Nums < itemdata.Num)
                        {
                            itemnums = itemdata.Num - item.Nums;
                            //获取包现在的成品信息
                            var jobitemdata = JobBookingQrCode.Where(x => x.MaterialId == item.MaterialId).ToList();
                            //获取实际扫描的成品信息
                            var sjitemdata = data.PackJobMaterial.Where(x => x.MaterialId == item.MaterialId).ToList();
                            foreach (var jitem in jobitemdata)
                            {
                                var jitemdata = sjitemdata.Where(x => x.Id == jitem.Id).FirstOrDefault();
                                if (jitemdata == null)
                                {
                                    jobids.Add(jitem.Id);
                                }
                            }
                            sqlMain += @" update PB_JobBookingQrCode set PackId=Null where Id in ('" + string.Join("','", jobids.ToArray()) + "'); ";
                            sqlMain += @" delete from PB_PackListInfo where JobBookingId in ('" + string.Join("','", jobids.ToArray()) + "');  ";
                            sqlMain += @" update PB_PackMaterialCount set Nums=" + item.Nums + " where PackId='" + packId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                            sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + itemnums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                            itemnums = itemdata.Num - item.Nums;
                            if (itemdata.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + itemnums + ",ScanNum=IFNULL(ScanNum,0)-" + itemnums + "  where MaterialId='" + itemdata.MaterialId + "' and LocalId='" + itemdata.LocalId + "'; ";
                            }
                            else if (itemdata.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + itemnums + ",ScanNum=IFNULL(ScanNum,0)-" + itemnums + "  where MaterialId='" + itemdata.MaterialId + "' and LocalId='" + itemdata.LocalId + "'; ";
                            }

                            TD_OutStorDetail outdetail = new TD_OutStorDetail();
                            outdetail.Id = IdHelper.GetId();
                            outdetail.StorId = itemdata.StorId;
                            outdetail.OutStorId = outid;
                            outdetail.LocalId = itemdata.LocalId;
                            outdetail.MaterialId = item.MaterialId;
                            outdetail.Price = Convert.ToDouble(itemdata.Price);
                            outdetail.TotalAmt = Convert.ToDouble(itemdata.Price * itemnums);
                            outdetail.LocalNum = 0;
                            outdetail.OutNum = Convert.ToDouble(itemnums);
                            outdetail.CreateTime = DateTime.Now;
                            outdetail.CreatorId = _operator.UserId;
                            outdetail.Deleted = false;
                            outdetail.OldOrNew = itemdata.OldOrNew;
                            OutStorDetail.Add(outdetail);

                            PB_StockLog slog = new PB_StockLog();
                            slog.Id = IdHelper.GetId();
                            slog.PackId = packId;
                            slog.MaterialId = itemdata.MaterialId;
                            slog.StorId = itemdata.StorId;
                            slog.LocationId = itemdata.LocalId;
                            slog.StockNumber = itemnums;
                            slog.CreatorId = _operator.UserId;
                            slog.Deleted = false;
                            slog.CreatorName = userdata.RealName;
                            slog.Type = 1;
                            slog.CreateTime = DateTime.Now;
                            slog.State = 1;
                            slog.OldOrNew = itemdata.OldOrNew;
                            slog.CirBillId = "";
                            slog.JobId = "";
                            StockLog.Add(slog);
                        }
                    }
                }


                sqlMain += @" update PB_PackList set Nums='" + data.PackJobMaterial.Count() + "' where Id='" + packId + "'; ";

                double? outnum = 0;
                double? outamoun = 0;
                if (OutStorDetail.Count > 0)
                {
                    foreach (var item in OutStorDetail)
                    {
                        TD_OutStorRecord outRecord = new TD_OutStorRecord();
                        outRecord.Id = IdHelper.GetId();
                        outRecord.StorId = item.StorId;
                        outRecord.OutStorId = outid;
                        outRecord.MaterialId = item.MaterialId;
                        outRecord.Price = item.Price;
                        outRecord.TotalAmt = item.TotalAmt;
                        outRecord.OutNum = item.OutNum;
                        outRecord.CreateTime = DateTime.Now;
                        outRecord.CreatorId = _operator.UserId;
                        outRecord.Deleted = false;
                        OutStorRecord.Add(outRecord);
                        outnum += item.OutNum;
                        outamoun += item.TotalAmt;
                    }

                    TD_OutStorage outdata = new TD_OutStorage();
                    outdata.Id = outid;
                    outdata.StorageId = OutStorRecord.FirstOrDefault().StorId;
                    outdata.Code = GetTimeStamp();
                    outdata.OutTime = DateTime.Now;
                    outdata.OutType = "OtherOut";
                    outdata.RefCode = "";
                    outdata.OutNum = outnum;
                    outdata.TotalAmt = outamoun;
                    outdata.Status = 0;
                    outdata.Remarks = "包盘点(包重置)";
                    outdata.CreateTime = DateTime.Now;
                    outdata.CreatorId = _operator.UserId;
                    outdata.Deleted = false;
                    outdata.QrCode = h_OutStorage + "," + outid;
                    outdata.DepId = userdata.DepartmentId;
                    outdata.FactoryId = userdata.FactoryId;
                    OutStorage.Add(outdata);

                    await Db.InsertAsync<TD_OutStorDetail>(OutStorDetail);

                    await Db.InsertAsync<TD_OutStorRecord>(OutStorRecord);

                    await Db.InsertAsync<TD_OutStorage>(OutStorage);
                }

                if (InStorDetail.Count > 0)
                {
                    foreach (var item in InStorDetail)
                    {
                        TD_InStorRecord record = new TD_InStorRecord();
                        record.Id = IdHelper.GetId();
                        record.InStorId = outid;
                        record.StorId = item.StorId;
                        record.MaterialId = item.MaterialId;
                        record.Price = item.Price;
                        record.TotalAmt = item.TotalAmt;
                        record.Num = item.Num;
                        record.CreateTime = DateTime.Now;
                        record.CreatorId = _operator.UserId;
                        record.Deleted = false;
                        InStorRecord.Add(record);

                        outnum += item.Num;
                        outamoun += item.TotalAmt;
                    }

                    TD_InStorage Storage = new TD_InStorage();
                    Storage.Id = outid;
                    Storage.RecId = "";
                    Storage.Code = GetTimeStamp();
                    Storage.InStorTime = DateTime.Now;
                    Storage.InType = "OtherType";
                    Storage.RefCode = "";
                    Storage.Remarks = "包盘点(包重置)";
                    Storage.StorId = InStorRecord.FirstOrDefault().StorId;
                    Storage.TotalNum = Convert.ToDouble(outnum);
                    Storage.TotalAmt = Convert.ToDouble(outamoun);
                    Storage.CreateTime = DateTime.Now;
                    Storage.CreatorId = _operator.UserId;
                    Storage.Deleted = false;
                    Storage.QrCode = h_Warehousing + "," + outid;
                    Storage.DepId = userdata.DepartmentId;
                    InStorage.Add(Storage);

                    await Db.InsertAsync<TD_InStorDetail>(InStorDetail);

                    await Db.InsertAsync<TD_InStorRecord>(InStorRecord);

                    await Db.InsertAsync<TD_InStorage>(InStorage);
                }

                await Db.InsertAsync<PB_StockLog>(StockLog);

                await ExecuteSqlAsync(sqlMain);
            }
        }

        /// <summary>
        /// 包重置保存(新版)2022-09-06
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        public async Task SavePackNumsDataAsync(PackJobDetailDTO data, MongoDBOptions _mongodbOptions)
        {
            //包Id
            string packId = data.PackQrCode.Split(',')?[1].ToString();

            //货位Id
            string LocaId = data.LocaQrCode.Split(',')?[1].ToString();

            PB_Location Location = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == LocaId).FirstOrDefaultAsync();

            PB_PackList PackList = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            var deptdata = await _opdept.GetOperatorDept();

            string sqlMain = string.Empty;
            //删除包明细
            sqlMain += @" delete from PB_PackListInfo where PackId='" + packId + "'; ";
            //清除包明细
            sqlMain += @" update PB_JobBookingQrCode set PackId=NULL where PackId='" + packId + "'; ";
            //清除包数量
            sqlMain += @" DELETE from PB_PackMaterialCount where PackId='" + packId + "'; ";

            //获取包原来的库存信息
            List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();
            if (LocalDetail.Count > 0)
            {
                foreach (var item in LocalDetail)
                {
                    IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.LocalId == item.LocalId && x.MaterialId == item.MaterialId).FirstOrDefaultAsync();
                    if (!LocalMaterial.IsNullOrEmpty())
                    {
                        if (LocalMaterial.ScanNum > item.Num)
                        {
                            if (item.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            else if (item.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                        }
                        else
                        {
                            if (item.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=0,ScanNum=0 where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            else if (item.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=0,ScanNum=0 where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                        }
                    }
                }
            }

            sqlMain += @" delete from IT_LocalDetail where PackId='" + packId + "'; ";

            List<PB_PackList> PackListData = new List<PB_PackList>();
            List<PB_PackListInfo> PackListInfo = new List<PB_PackListInfo>();
            List<PB_PackMaterialCount> PackMaterialCount = new List<PB_PackMaterialCount>();
            List<PrintQueue> PrintQueueList = new List<PrintQueue>();
            List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
            List<IT_LocalMaterial> LocalMaterialList = new List<IT_LocalMaterial>();

            List<string> jobids = new List<string>();
            //添加包明细
            foreach (var item in data.PackJobMaterial)
            {
                PB_PackListInfo info = new PB_PackListInfo();
                info.Id = IdHelper.GetId();
                info.PackId = packId;
                info.JobBookingId = item.Id;
                info.CreatorId = _operator.UserId;
                info.Deleted = false;
                info.CreatorName = "";
                info.OldOrNew = 1;
                info.CreatorTime = DateTime.Now;
                PackListInfo.Add(info);

                jobids.Add(item.Id);

                sqlMain += @" delete from IT_LocalDetail where JobId='" + item.Id + "'; ";
            }
            //修改成品码与包的团溪
            sqlMain += @" update PB_JobBookingQrCode set PackId='" + packId + "' where Id in ('" + string.Join("','", jobids.ToArray()) + "'); ";

            List<IT_LocalDetail> joblocadetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => jobids.Contains(x.JobId)).ToListAsync();
            var jobdetail = joblocadetail.GroupBy(x => new { x.LocalId, x.MaterialId }).Select(x => new { LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.Num) }).ToList();
            if (jobdetail.Count > 0)
            {
                foreach (var item in jobdetail)
                {
                    IT_LocalMaterial itemMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.LocalId == item.LocalId && x.MaterialId == item.MaterialId).FirstOrDefaultAsync();
                    if (!itemMaterial.IsNullOrEmpty())
                    {
                        if (itemMaterial.ScanNum > item.Nums)
                        {
                            sqlMain += @" update  IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)-" + item.Nums + " where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "' ;";
                        }
                        else
                        {
                            sqlMain += @" update  IT_LocalMaterial set Nums_N=0,ScanNum=0 where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "' ;";
                        }
                    }
                }
            }


            var jobmaterial = data.PackJobMaterial.GroupBy(x => new { x.MaterialId, x.MaterialName }).Select(x => new { MaterialId = x.Key.MaterialId, MaterialName = x.Key.MaterialName, Nums = x.Count() }).ToList();

            double? packnums = 0;

            List<string> Materialids = new List<string>();

            //添加包的数量
            foreach (var item in jobmaterial)
            {
                PB_PackMaterialCount pmc = new PB_PackMaterialCount();
                pmc.Id = IdHelper.GetId();
                pmc.PackId = packId;
                pmc.MaterialId = item.MaterialId;
                pmc.Nums = item.Nums;
                PackMaterialCount.Add(pmc);
                Materialids.Add(item.MaterialId);
                packnums += item.Nums;

                IT_LocalDetail locadetaildata = new IT_LocalDetail();
                locadetaildata.Id = IdHelper.GetId();
                locadetaildata.StorId = Location.StorId;
                locadetaildata.LocalId = LocaId;
                locadetaildata.MaterialId = item.MaterialId;
                locadetaildata.BarCode = h_Pack + "," + packId;
                locadetaildata.InTime = DateTime.Now;
                locadetaildata.CreateTime = DateTime.Now;
                locadetaildata.CreatorId = _operator.UserId;
                locadetaildata.Deleted = false;
                locadetaildata.Num = item.Nums;
                locadetaildata.PackId = packId;
                locadetaildata.OldOrNew = 1;
                locadetaildata.RecId = "";
                locadetaildata.JobId = "";
                LocalDetailList.Add(locadetaildata);

                IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.LocalId == LocaId && x.MaterialId == item.MaterialId).FirstOrDefaultAsync();
                if (LocalMaterial.IsNullOrEmpty())
                {
                    IT_LocalMaterial itemmaterial = new IT_LocalMaterial();
                    itemmaterial.Id = IdHelper.GetId();
                    itemmaterial.MaterialId = item.MaterialId;
                    itemmaterial.StorId = Location.StorId;
                    itemmaterial.LocalId = LocaId;
                    itemmaterial.Nums_N = item.Nums;
                    itemmaterial.Nums_O = 0;
                    itemmaterial.Nums_R = 0;
                    itemmaterial.CreatorId = _operator.UserId;
                    itemmaterial.CreateTime = DateTime.Now;
                    itemmaterial.Deleted = false;
                    itemmaterial.AreaId = Location.AreaId;
                    itemmaterial.RackId = Location.RackId;
                    itemmaterial.ScanNum = item.Nums;
                    itemmaterial.CheckNum = 0;
                    LocalMaterialList.Add(itemmaterial);

                }
                else
                {
                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where LocalId='" + LocaId + "' and MaterialId='" + item.MaterialId + "'; ";
                }
            }

            List<PB_Material> Material = await Db.GetIQueryable<PB_Material>().Where(x => Materialids.Contains(x.Id)).ToListAsync();

            if (PackList != null)
            {
                //包存在修改包的信息
                if (!PackList.InStorTime.IsNullOrEmpty())
                {
                    if (jobmaterial.Count == 1)
                    {
                        sqlMain += @"  UPDATE PB_PackList SET Status=3,Nums=" + packnums + ",PackageType=0,MaterialId='" + jobmaterial.FirstOrDefault().MaterialId + "',BoxName='" + jobmaterial.FirstOrDefault().MaterialName + "' WHERE Id='" + packId + "'; ";
                    }
                    else
                    {
                        sqlMain += @"  UPDATE PB_PackList SET Status=3,Nums=" + packnums + ",PackageType=1,MaterialId='',BoxName='" + (jobmaterial.FirstOrDefault().MaterialName + "(混合)") + "' WHERE Id='" + packId + "'; ";
                    }
                }
                else
                {
                    if (jobmaterial.Count == 1)
                    {
                        sqlMain += @"  UPDATE PB_PackList SET Status=3,Nums=" + packnums + ",PackageType=0,MaterialId='" + jobmaterial.FirstOrDefault().MaterialId + "',BoxName='" + jobmaterial.FirstOrDefault().MaterialName + "',InStorTime=NOW() WHERE Id='" + packId + "'; ";
                    }
                    else
                    {
                        sqlMain += @"  UPDATE PB_PackList SET Status=3,Nums=" + packnums + ",PackageType=1,MaterialId='',BoxName='" + (jobmaterial.FirstOrDefault().MaterialName + "(混合)") + "',InStorTime=NOW() WHERE Id='" + packId + "'; ";
                    }
                }

                PrintQueue materprint = new PrintQueue();
                materprint.Id = packId;
                materprint.No = packId;
                materprint.Name = jobmaterial.Count == 1 ? jobmaterial.FirstOrDefault().MaterialName : jobmaterial.FirstOrDefault().MaterialName + "(混合)";
                materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                materprint.Dept = deptdata.DeptName;
                materprint.QrCode = data.PackQrCode;
                materprint.Type = Skill_Type.Package.ToString();
                materprint.Status = packnums.ToString();
                materprint.Printer = data.PrintId;
                materprint.TypeName = Material.Where(x => x.Id == jobmaterial.FirstOrDefault().MaterialId).FirstOrDefault().Spec;
                materprint.BatchNumber = Guid.NewGuid().ToString("N");
                materprint.JobCount = 1;
                materprint.ProjectName = "";
                materprint.BuildingNumberName = "";
                materprint.IsStandard = 0;
                PrintQueueList.Add(materprint);
            }
            else
            {
                //包不存在创建包
                PB_PackList pacdata = new PB_PackList();
                pacdata.Id = packId;
                pacdata.DeptId = userdata.FactoryId;
                pacdata.BoxNo = "bag_" + GetTimeStamp();
                if (jobmaterial.Count == 1)
                {
                    pacdata.BoxName = jobmaterial.FirstOrDefault().MaterialName;
                    pacdata.MaterialId = jobmaterial.FirstOrDefault().MaterialId;
                    pacdata.PackageType = 0;
                }
                else
                {
                    pacdata.BoxName = jobmaterial.FirstOrDefault().MaterialName+"(混合)";
                    pacdata.MaterialId = "";
                    pacdata.PackageType = 1;
                }
                pacdata.Status = 3;
                pacdata.TaskId = "";
                pacdata.Type = 1;
                pacdata.Nums = packnums;
                pacdata.State = false;
                pacdata.CreateTime = DateTime.Now;
                pacdata.NoticeId = "";
                pacdata.CreatorId = _operator.UserId;
                pacdata.Deleted = false;
                pacdata.CreatorName = userdata.RealName;
                pacdata.QrCode = data.PackQrCode;
                pacdata.WorkshopId = userdata.DepartmentId;
                pacdata.OldOrNew = 1;
                pacdata.IsUnpacking = false;
                pacdata.InStorTime = DateTime.Now;
                PackListData.Add(pacdata);

                PrintQueue materprint = new PrintQueue();
                materprint.Id = packId;
                materprint.No = packId;
                materprint.Name = jobmaterial.Count == 1 ? jobmaterial.FirstOrDefault().MaterialName : jobmaterial.FirstOrDefault().MaterialName + "(混合)";
                materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                materprint.Dept = deptdata.DeptName;
                materprint.QrCode = data.PackQrCode;
                materprint.Type = Skill_Type.Package.ToString();
                materprint.Status = packnums.ToString();
                materprint.Printer = data.PrintId;
                materprint.TypeName = Material.Where(x => x.Id == jobmaterial.FirstOrDefault().MaterialId).FirstOrDefault().Spec;
                materprint.BatchNumber = Guid.NewGuid().ToString("N");
                materprint.JobCount = 1;
                materprint.ProjectName = "";
                materprint.BuildingNumberName = "";
                materprint.IsStandard = 0;
                PrintQueueList.Add(materprint);

            }


            await Db.ExecuteSqlAsync(sqlMain);

            await Db.InsertAsync<PB_PackListInfo>(PackListInfo);
            await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCount);
            await Db.InsertAsync<PB_PackList>(PackListData);

            await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);
            await Db.InsertAsync<IT_LocalMaterial>(LocalMaterialList);

            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, PrintQueueList);

        }

        #endregion

        #region 调整盘差逻辑2022--8-26(增加盘点库存明细记录)

        /// <summary>
        /// 获取库存信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<CheckStockDetailDTO> GetCheckStockDetailAsync(TDcheckDataDTO data)
        {
            CheckStockDetailDTO checkstock = new CheckStockDetailDTO();
            if (data.CheckData.Count > 0)
            {
                var check = data.CheckData.GroupBy(x => new { x.CheckId }).Select(x => new { CheckId = x.Key.CheckId }).FirstOrDefault();

                TD_Check tdcheck = await Db.GetIQueryable<TD_Check>().Where(x => x.Id == check.CheckId).FirstOrDefaultAsync();
                //获取盘差值为整数的明细的货位信息
                var pnlocadata = data.CheckData.GroupBy(x => new { x.localId }).Select(x => new { localId = x.Key.localId }).ToList();
                List<string> locaIds = new List<string>();
                foreach (var item in pnlocadata)
                {
                    locaIds.Add(item.localId);
                }
                //获取盘差值为整数的明细的物料信息
                var material = data.CheckData.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                List<string> materialIds = new List<string>();
                foreach (var item in material)
                {
                    materialIds.Add(item.MaterialId);
                }
                //获取库存明细货位明细上的物料信息
                string sqldetail = @" select * from IT_LocalDetail where MaterialId in ('" + string.Join("','", materialIds.ToArray()) + "') and LocalId in ('" + string.Join("','", locaIds.ToArray()) + "') ";
                List<IT_LocalDetail> LocalDetail = await Db.GetListBySqlAsync<IT_LocalDetail>(sqldetail);

                //获取库存汇总货位明细上的物料信息
                string sqlMian = @" select * from IT_LocalMaterial where MaterialId in ('" + string.Join("','", materialIds.ToArray()) + "') and LocalId in ('" + string.Join("','", locaIds.ToArray()) + "') ";
                List<IT_LocalMaterial> LocalMaterial = await Db.GetListBySqlAsync<IT_LocalMaterial>(sqlMian);

                //获取要盘点的物料信息
                string sqlMater = @" select * from PB_Material where Id in ('" + string.Join("','", materialIds.ToArray()) + "') ";
                List<PB_Material> MaterialList = await Db.GetListBySqlAsync<PB_Material>(sqlMater);

                checkstock.LocalDetailList = LocalDetail;
                checkstock.LocalMaterialList = LocalMaterial;
                checkstock.MaterialList = MaterialList;
            }
            else
            {
                var check = data.CheckPack.GroupBy(x => new { x.CheckId }).Select(x => new { CheckId = x.Key.CheckId }).FirstOrDefault();

                TD_Check tdcheck = await Db.GetIQueryable<TD_Check>().Where(x => x.Id == check.CheckId).FirstOrDefaultAsync();
                //获取实际盘点的货位信息
                var pnlocadata = data.CheckPack.GroupBy(x => new { x.localId }).Select(x => new { localId = x.Key.localId }).ToList();
                List<string> locaIds = new List<string>();
                foreach (var item in pnlocadata)
                {
                    locaIds.Add(item.localId);
                }
                //获取实际盘点的物料信息
                var material = data.CheckPack.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                List<string> materialIds = new List<string>();
                foreach (var item in material)
                {
                    materialIds.Add(item.MaterialId);
                }
                //获取库存明细实际盘点货位的物料信息
                string sqldetail = @" select * from IT_LocalDetail where MaterialId in ('" + string.Join("','", materialIds.ToArray()) + "') and LocalId in ('" + string.Join("','", locaIds.ToArray()) + "') ";
                List<IT_LocalDetail> LocalDetail = await Db.GetListBySqlAsync<IT_LocalDetail>(sqldetail);
                //获取库存汇总实际盘点货位的物料信息
                string sqlMian = @" select * from IT_LocalMaterial where MaterialId in ('" + string.Join("','", materialIds.ToArray()) + "') and LocalId in ('" + string.Join("','", locaIds.ToArray()) + "') ";
                List<IT_LocalMaterial> LocalMaterial = await Db.GetListBySqlAsync<IT_LocalMaterial>(sqlMian);
                //获取实际盘点的物料信息
                string sqlMater = @" select * from PB_Material where Id in ('" + string.Join("','", materialIds.ToArray()) + "') ";
                List<PB_Material> MaterialList = await Db.GetListBySqlAsync<PB_Material>(sqlMater);

                checkstock.LocalDetailList = LocalDetail;
                checkstock.LocalMaterialList = LocalMaterial;
                checkstock.MaterialList = MaterialList;
            }

            return checkstock;
        }

        /// <summary>
        /// 计算盘差值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<DiscDifferenceDTO> GetDiscDifferenceMaterialAsync(DifferenceDTO data)
        {
            string sqlMain = string.Empty;
            DiscDifferenceDTO dddata = new DiscDifferenceDTO();
            List<PB_StockLog> StockLog = new List<PB_StockLog>();
            List<TD_InStorDetail> InStorDetail = new List<TD_InStorDetail>();
            List<TD_OutStorDetail> OutStorDetail = new List<TD_OutStorDetail>();
            List<TD_CheckStockDetail> CheckStockDetail = new List<TD_CheckStockDetail>();

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //查询盘点单信息
            TD_Check Check = await Db.GetIQueryable<TD_Check>().Where(x => x.Id == data.checkId).FirstOrDefaultAsync();

            if (data.CheckData.Count > 0)
            {
                //根据盘点完成情况生成出入库单明细
                //入库单明细
                string InStorId = IdHelper.GetId();
                var justcheckdata = data.CheckData.Where(x => x.DisNum > 0).ToList();
                foreach (var item in justcheckdata)
                {
                    var itemdata = data.MaterialList.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                    TD_InStorDetail InStor = new TD_InStorDetail();
                    InStor.Id = IdHelper.GetId();
                    InStor.InStorId = InStorId;
                    InStor.StorId = item.StorId;
                    InStor.LocalId = item.localId;
                    InStor.MaterialId = item.MaterialId;
                    InStor.Price = Convert.ToDouble(itemdata == null ? 0 : itemdata.Price);
                    InStor.TotalAmt = Convert.ToDouble((itemdata == null ? 0 : itemdata.Price) * item.DisNum);
                    InStor.Num = Convert.ToDouble(item.DisNum);
                    InStor.CreateTime = DateTime.Now;
                    InStor.CreatorId = _operator.UserId;
                    InStor.Deleted = false;
                    InStor.PackId = "";
                    InStor.OldOrNew = 1;
                    InStor.TaskId = "";
                    InStor.JobId = "";
                    InStorDetail.Add(InStor);

                    PB_StockLog log = new PB_StockLog();
                    log.Id = IdHelper.GetId();
                    log.PackId = "";
                    log.MaterialId = item.MaterialId;
                    log.StorId = item.StorId;
                    log.LocationId = item.localId;
                    log.StockNumber = item.DisNum;
                    log.CreatorId = _operator.UserId;
                    log.Deleted = false;
                    log.CreatorName = userdata.RealName;
                    log.Type = 1;
                    log.OrderID = data.checkId;
                    log.CreateTime = DateTime.Now;
                    log.State = 1;
                    log.OldOrNew = 1;
                    log.CirBillId = "";
                    log.JobId = "";
                    StockLog.Add(log);
                }

                //出库单明细
                string OutStorId = IdHelper.GetId();
                var negativecheckdata = data.CheckData.Where(x => x.DisNum < 0).ToList();
                foreach (var item in negativecheckdata)
                {
                    //获取物料信息
                    var itemdata = data.MaterialList.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                    //获取当前货位物料的库存信息
                    var itemlocamaterial = data.LocalMaterialList.Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.localId).FirstOrDefault();
                    double? dnums = 0;
                    if (item.CheckNum == 0)
                    {
                        dnums = itemlocamaterial == null ? 0 : itemlocamaterial.ScanNum;
                    }
                    else
                    {
                        dnums = (-item.DisNum);
                    }

                    TD_OutStorDetail OutStor = new TD_OutStorDetail();
                    OutStor.Id = IdHelper.GetId();
                    OutStor.StorId = item.StorId;
                    OutStor.OutStorId = OutStorId;
                    OutStor.LocalId = item.localId;
                    OutStor.MaterialId = item.MaterialId;
                    OutStor.Price = Convert.ToDouble(itemdata == null ? 0 : itemdata.Price);
                    OutStor.TotalAmt = Convert.ToDouble(dnums * (itemdata == null ? 0 : itemdata.Price));
                    OutStor.OutNum = Convert.ToDouble(dnums);
                    OutStor.CreateTime = DateTime.Now;
                    OutStor.CreatorId = _operator.UserId;
                    OutStor.Deleted = false;
                    OutStor.OldOrNew = 1;
                    OutStorDetail.Add(OutStor);

                    PB_StockLog log = new PB_StockLog();
                    log.Id = IdHelper.GetId();
                    log.PackId = "";
                    log.MaterialId = item.MaterialId;
                    log.StorId = item.StorId;
                    log.LocationId = item.localId;
                    log.StockNumber = (dnums);
                    log.CreatorId = _operator.UserId;
                    log.Deleted = false;
                    log.CreatorName = userdata.RealName;
                    log.Type = 1;
                    log.OrderID = data.checkId;
                    log.CreateTime = DateTime.Now;
                    log.State = 0;
                    log.OldOrNew = 1;
                    log.CirBillId = "";
                    log.JobId = "";
                    StockLog.Add(log);
                }

                //把库存明细添加到盘点库存记录表中
                foreach (var item in data.LocalDetailList)
                {
                    TD_CheckStockDetail StockDetail = new TD_CheckStockDetail();
                    StockDetail.Id = IdHelper.GetId();
                    StockDetail.CheckId = data.checkId;
                    StockDetail.StorId = item.StorId;
                    StockDetail.LocalId = item.LocalId;
                    StockDetail.MaterialId = item.MaterialId;
                    StockDetail.PackId = item.PackId;
                    StockDetail.JobId = item.JobId;
                    StockDetail.OldOrNew = item.OldOrNew;
                    StockDetail.Nums = item.Num;
                    StockDetail.CreatorId = _operator.UserId;
                    StockDetail.CreateTime = DateTime.Now;
                    CheckStockDetail.Add(StockDetail);

                    //比较库中的包是实际盘点的包信息
                    if (!item.PackId.IsNullOrEmpty())
                    {
                        var itemdata = data.CheckPack.Where(x => x.PackId == item.PackId && x.localId == item.LocalId).FirstOrDefault();
                        if (itemdata != null)
                        {
                            sqlMain += @" update PB_PackList set Status=4,OutStorTime=NOW(),OutStorUserId='" + _operator.UserId + "',OutStorUserName='" + userdata.RealName + "' where Id='" + item.PackId + "'; ";
                        }
                    }
                }

                //处理实际盘点的包信息
                foreach (var item in data.CheckPack)
                {
                    if (!item.PackId.IsNullOrEmpty())
                    {
                        sqlMain += @" update PB_PackList set Status=3,InStorTime=NOW(),InStorUserId='" + _operator.UserId + "',InStorUserName='" + userdata.RealName + "',OutStorTime=NULL,OutStorUserId=NULL,OutStorUserName=NULL  where Id='" + item.PackId + "' ; ";
                        sqlMain += @" delete from IT_LocalDetail where PackId='" + item.PackId + "'; ";
                    }
                    if (!item.JobId.IsNullOrEmpty())
                    {
                        sqlMain += @" delete from IT_LocalDetail where JobId='" + item.JobId + "'; ";
                    }
                }

                List<string> locaids = new List<string>();
                List<string> materialids = new List<string>();

                //获取盘点单的货位信息
                var locadata = data.CheckData.GroupBy(x => new { x.localId }).Select(x => new { localId = x.Key.localId }).ToList();
                foreach (var item in locadata)
                {
                    locaids.Add(item.localId);
                }

                //获取盘点单的物料信息
                var materialdata = data.CheckData.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                foreach (var item in materialdata)
                {
                    materialids.Add(item.MaterialId);
                }

                if (Check.Type != "3")
                {
                    //删除库存明细
                    sqlMain += @" delete from IT_LocalDetail where  LocalId in ('" + string.Join("','", locaids.ToArray()) + "'); ";
                    sqlMain += @" delete from IT_LocalMaterial where  LocalId in ('" + string.Join("','", locaids.ToArray()) + "'); ";
                }
                else if (Check.Type == "3")
                {
                    //删除库存明细
                    sqlMain += @" delete from IT_LocalDetail where  LocalId in ('" + string.Join("','", locaids.ToArray()) + "') and MaterialId in ('" + string.Join("','", materialids.ToArray()) + "') ; ";
                    sqlMain += @" delete from IT_LocalMaterial where  LocalId in ('" + string.Join("','", locaids.ToArray()) + "') and MaterialId in ('" + string.Join("','", materialids.ToArray()) + "') ; ";
                }
                //获取备货单占用量
                string stocklistsql = @"select lm.MaterialId,lm.LocalId,(t.StockVolume-t.ReadyNums)Nums from
 IT_LocalMaterial as lm join (
select b.MaterialId,b.LocationId,SUM(b.StockVolume) as StockVolume,SUM(b.ReadyNums) as ReadyNums from PB_PickUpMain as a
left join PB_PickUpList as b on a.Id=b.ParentId where a.`Status`<3 group by MaterialId,LocationId
)as t on lm.MaterialId=t.MaterialId and lm.LocalId=t.LocationId
";
                List<PickMaterialOccupyDTO> PickMaterialList = await Db.GetListBySqlAsync<PickMaterialOccupyDTO>(stocklistsql);

                dddata.StockLog = StockLog;
                dddata.InStorDetail = InStorDetail;
                dddata.OutStorDetail = OutStorDetail;
                dddata.CheckStockDetail = CheckStockDetail;
                dddata.PickMaterialOccupy = PickMaterialList;
                dddata.SqlMain = sqlMain;
            }
            else
            {
                //根据盘点完成情况生成出入库单明细
                //入库单明细
                string InStorId = IdHelper.GetId();
                foreach (var item in data.CheckPack)
                {
                    var itemdata = data.MaterialList.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                    TD_InStorDetail InStor = new TD_InStorDetail();
                    InStor.Id = IdHelper.GetId();
                    InStor.InStorId = InStorId;
                    InStor.StorId = item.StorId;
                    InStor.LocalId = item.localId;
                    InStor.MaterialId = item.MaterialId;
                    InStor.Price = Convert.ToDouble(itemdata == null ? 0 : itemdata.Price);
                    InStor.TotalAmt = Convert.ToDouble((itemdata == null ? 0 : itemdata.Price) * item.Nums);
                    InStor.Num = Convert.ToDouble(item.Nums);
                    InStor.CreateTime = DateTime.Now;
                    InStor.CreatorId = _operator.UserId;
                    InStor.Deleted = false;
                    InStor.PackId = "";
                    InStor.OldOrNew = 1;
                    InStor.TaskId = "";
                    InStor.JobId = "";
                    InStorDetail.Add(InStor);

                    PB_StockLog log = new PB_StockLog();
                    log.Id = IdHelper.GetId();
                    log.PackId = "";
                    log.MaterialId = item.MaterialId;
                    log.StorId = item.StorId;
                    log.LocationId = item.localId;
                    log.StockNumber = item.Nums;
                    log.CreatorId = _operator.UserId;
                    log.Deleted = false;
                    log.CreatorName = userdata.RealName;
                    log.Type = 1;
                    log.OrderID = data.checkId;
                    log.CreateTime = DateTime.Now;
                    log.State = 1;
                    log.OldOrNew = 1;
                    log.CirBillId = "";
                    log.JobId = "";
                    StockLog.Add(log);
                }

                //把库存明细添加到盘点库存记录表中
                foreach (var item in data.LocalDetailList)
                {
                    TD_CheckStockDetail StockDetail = new TD_CheckStockDetail();
                    StockDetail.Id = IdHelper.GetId();
                    StockDetail.CheckId = data.checkId;
                    StockDetail.StorId = item.StorId;
                    StockDetail.LocalId = item.LocalId;
                    StockDetail.MaterialId = item.MaterialId;
                    StockDetail.PackId = item.PackId;
                    StockDetail.JobId = item.JobId;
                    StockDetail.OldOrNew = item.OldOrNew;
                    StockDetail.Nums = item.Num;
                    StockDetail.CreatorId = _operator.UserId;
                    StockDetail.CreateTime = DateTime.Now;
                    CheckStockDetail.Add(StockDetail);

                    //比较库中的包是实际盘点的包信息
                    if (!item.PackId.IsNullOrEmpty())
                    {
                        var itemdata = data.CheckPack.Where(x => x.PackId == item.PackId && x.localId == item.LocalId).FirstOrDefault();
                        if (itemdata != null)
                        {
                            sqlMain += @" update PB_PackList set Status=4,OutStorTime=NOW(),OutStorUserId='" + _operator.UserId + "',OutStorUserName='" + userdata.RealName + "' where Id='" + item.PackId + "'; ";
                        }
                    }
                }

                //处理实际盘点的包信息
                foreach (var item in data.CheckPack)
                {
                    if (!item.PackId.IsNullOrEmpty())
                    {
                        sqlMain += @" update PB_PackList set Status=3,InStorTime=NOW(),InStorUserId='" + _operator.UserId + "',InStorUserName='" + userdata.RealName + "',OutStorTime=NULL,OutStorUserId=NULL,OutStorUserName=NULL where Id='" + item.PackId + "' ; ";
                        sqlMain += @" delete from IT_LocalDetail where PackId='" + item.PackId + "'; ";
                    }
                    if (!item.JobId.IsNullOrEmpty())
                    {
                        sqlMain += @" delete from IT_LocalDetail where JobId='" + item.JobId + "'; ";
                    }
                }

                //获取盘点单的货位信息
                List<string> locaids = new List<string>();
                var locadata = data.CheckPack.GroupBy(x => new { x.localId }).Select(x => new { localId = x.Key.localId }).ToList();
                foreach (var item in locadata)
                {
                    locaids.Add(item.localId);
                }

                //获取盘点单的物料信息
                List<string> materialids = new List<string>();
                var materialdata = data.CheckPack.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                foreach (var item in materialdata)
                {
                    materialids.Add(item.MaterialId);
                }

                if (Check.Type != "3")
                {
                    //删除库存明细
                    sqlMain += @" delete from IT_LocalDetail where  LocalId in ('" + string.Join("','", locaids.ToArray()) + "'); ";
                    sqlMain += @" delete from IT_LocalMaterial where  LocalId in ('" + string.Join("','", locaids.ToArray()) + "'); ";
                }
                else if (Check.Type == "3")
                {
                    //删除库存明细
                    sqlMain += @" delete from IT_LocalDetail where  LocalId in ('" + string.Join("','", locaids.ToArray()) + "') and MaterialId  in ('" + string.Join("','", materialids.ToArray()) + "') ; ";
                    sqlMain += @" delete from IT_LocalMaterial where  LocalId in ('" + string.Join("','", locaids.ToArray()) + "') and MaterialId  in ('" + string.Join("','", materialids.ToArray()) + "') ; ";
                }
                //获取备货单占用量
                string stocklistsql = @"select lm.MaterialId,lm.LocalId,(t.StockVolume-t.ReadyNums)Nums from
 IT_LocalMaterial as lm join (
select b.MaterialId,b.LocationId,SUM(b.StockVolume) as StockVolume,SUM(b.ReadyNums) as ReadyNums from PB_PickUpMain as a
left join PB_PickUpList as b on a.Id=b.ParentId where a.`Status`<3 group by MaterialId,LocationId
)as t on lm.MaterialId=t.MaterialId and lm.LocalId=t.LocationId
";
                List<PickMaterialOccupyDTO> PickMaterialList = await Db.GetListBySqlAsync<PickMaterialOccupyDTO>(stocklistsql);

                dddata.StockLog = StockLog;
                dddata.InStorDetail = InStorDetail;
                dddata.OutStorDetail = OutStorDetail;
                dddata.CheckStockDetail = CheckStockDetail;
                dddata.PickMaterialOccupy = PickMaterialList;
                dddata.SqlMain = sqlMain;
            }
            return dddata;
        }

        /// <summary>
        /// 盘差(同步处理)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public void SaveDifference(DifferenceDTO data)
        {
            try
            {

                if (!data.SqlMain.IsNullOrEmpty())
                {
                    //先删除库存明细
                    Db.ExecuteSql(data.SqlMain);
                }

                List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
                List<IT_LocalMaterial> CheckLocalMaterialList = new List<IT_LocalMaterial>();

                List<TD_InStorDetail> InStorDetailList = data.InStorDetail;
                List<TD_InStorRecord> InStorRecordList = new List<TD_InStorRecord>();
                List<TD_InStorage> InStorageList = new List<TD_InStorage>();

                List<TD_OutStorDetail> OutStorDetailList = data.OutStorDetail;
                List<TD_OutStorRecord> OutStorRecordList = new List<TD_OutStorRecord>();
                List<TD_OutStorage> OutStorageList = new List<TD_OutStorage>();

                Base_User userdata = Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefault();

                List<PB_Location> Location = Db.GetIQueryable<PB_Location>().ToList();


                //生成入库单
                if (data.InStorDetail != null)
                {
                    if (data.InStorDetail.Count > 0)
                    {
                        foreach (var item in data.InStorDetail)
                        {
                            TD_InStorRecord InRecord = new TD_InStorRecord();
                            InRecord.Id = IdHelper.GetId();
                            InRecord.InStorId = item.InStorId;
                            InRecord.StorId = item.StorId;
                            InRecord.MaterialId = item.MaterialId;
                            InRecord.Price = item.Price;
                            InRecord.TotalAmt = item.TotalAmt;
                            InRecord.Num = item.Num;
                            InRecord.CreateTime = DateTime.Now;
                            InRecord.CreatorId = _operator.UserId;
                            InRecord.Deleted = false;
                            InStorRecordList.Add(InRecord);
                        }

                        var Indata = InStorRecordList.GroupBy(x => new { x.InStorId, x.StorId }).Select(x => new { InStorId = x.Key.InStorId, StorId = x.Key.StorId, Nums = x.Sum(i => i.Num), TotalAmt = x.Sum(i => i.TotalAmt) }).FirstOrDefault();

                        TD_InStorage InStorage = new TD_InStorage();
                        InStorage.Id = Indata.InStorId;
                        InStorage.RecId = "";
                        InStorage.Code = GetTimeStamp();
                        InStorage.InType = "OtherType";
                        InStorage.InStorTime = DateTime.Now;
                        InStorage.RefCode = data.checkId;
                        InStorage.Status = 0;
                        InStorage.Remarks = "盘点单盘盈";
                        InStorage.StorId = Indata.StorId;
                        InStorage.TotalNum = Indata.Nums;
                        InStorage.TotalAmt = Indata.TotalAmt;
                        InStorage.CreateTime = DateTime.Now;
                        InStorage.CreatorId = _operator.UserId;
                        InStorage.Deleted = false;
                        InStorage.QrCode = h_Warehousing + "," + Indata.InStorId;
                        InStorage.DepId = userdata.DepartmentId;
                        InStorageList.Add(InStorage);

                    }
                }

                //生成出库单
                if (data.OutStorDetail != null)
                {
                    if (data.OutStorDetail.Count > 0)
                    {
                        foreach (var item in data.OutStorDetail)
                        {
                            TD_OutStorRecord OutRecord = new TD_OutStorRecord();
                            OutRecord.Id = IdHelper.GetId();
                            OutRecord.StorId = item.StorId;
                            OutRecord.OutStorId = item.OutStorId;
                            OutRecord.MaterialId = item.MaterialId;
                            OutRecord.Price = item.Price;
                            OutRecord.TotalAmt = item.TotalAmt;
                            OutRecord.OutNum = item.OutNum;
                            OutRecord.CreateTime = DateTime.Now;
                            OutRecord.CreatorId = _operator.UserId;
                            OutRecord.Deleted = false;
                            OutStorRecordList.Add(OutRecord);
                        }
                        var outdata = OutStorRecordList.GroupBy(x => new { x.OutStorId, x.StorId }).Select(x => new { OutStorId = x.Key.OutStorId, StorId = x.Key.StorId, Nums = x.Sum(i => i.OutNum), TotalAmt = x.Sum(i => i.TotalAmt) }).FirstOrDefault();

                        TD_OutStorage OutStorage = new TD_OutStorage();
                        OutStorage.Id = outdata.OutStorId;
                        OutStorage.StorageId = outdata.StorId;
                        OutStorage.Code = GetTimeStamp();
                        OutStorage.OutTime = DateTime.Now;
                        OutStorage.OutType = "OtherOut";
                        OutStorage.RefCode = data.checkId;
                        OutStorage.OutNum = outdata.Nums;
                        OutStorage.TotalAmt = outdata.TotalAmt;
                        OutStorage.Status = 0;
                        OutStorage.Remarks = "盘点单盘亏";
                        OutStorage.CreateTime = DateTime.Now;
                        OutStorage.CreatorId = _operator.UserId;
                        OutStorage.Deleted = false;
                        OutStorage.QrCode = h_OutStorage + "," + outdata.OutStorId;
                        OutStorage.DepId = userdata.DepartmentId;
                        OutStorage.ProjectId = "";
                        OutStorage.DesignId = "";
                        OutStorage.FactoryId = userdata.FactoryId;
                        OutStorageList.Add(OutStorage);

                    }
                }

                //根据实际盘点情况插入库存明细
                foreach (var item in data.CheckPack)
                {
                    var itemdata = data.MaterialList.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                    IT_LocalDetail LocalDetail = new IT_LocalDetail();
                    LocalDetail.Id = IdHelper.GetId();
                    LocalDetail.StorId = item.StorId;
                    LocalDetail.LocalId = item.localId;
                    LocalDetail.MaterialId = item.MaterialId;
                    LocalDetail.MeasureId = itemdata == null ? "" : itemdata.storageId;
                    if (!item.PackId.IsNullOrEmpty())
                    {
                        LocalDetail.BarCode = h_Pack + "," + item.PackId;
                    }
                    else if (!item.JobId.IsNullOrEmpty())
                    {
                        LocalDetail.BarCode = h_FinishedProduct + "," + item.JobId;
                    }
                    else
                    {
                        LocalDetail.BarCode = h_Material + "," + item.MaterialId;
                    }
                    LocalDetail.InTime = DateTime.Now;
                    LocalDetail.Amount = Convert.ToDouble(item.Nums * (itemdata == null ? 0 : itemdata.Price));
                    LocalDetail.CreateTime = DateTime.Now;
                    LocalDetail.CreatorId = _operator.UserId;
                    LocalDetail.Price = itemdata == null ? 0 : itemdata.Price;
                    LocalDetail.Deleted = false;
                    LocalDetail.Num = item.Nums;
                    LocalDetail.PackId = item.PackId;
                    LocalDetail.OldOrNew = item.OldOrNew;
                    LocalDetail.RecId = "";
                    LocalDetail.JobId = item.JobId;
                    LocalDetailList.Add(LocalDetail);
                }


                //获取盘点单实际盘点数据并汇总库存汇总信息
                var checkpackmaterial = data.CheckPack.GroupBy(x => new { x.StorId, x.localId, x.MaterialId, x.OldOrNew }).Select(x => new { StorId = x.Key.StorId, localId = x.Key.localId, MaterialId = x.Key.MaterialId, OldOrNew = x.Key.OldOrNew, Nums = x.Sum(i => i.Nums) }).ToList();

                //获取实际盘点数据货位的物料信息
                var checkpackmaterialdata = data.CheckPack.GroupBy(x => new { x.StorId, x.localId, x.MaterialId }).Select(x => new { StorId = x.Key.StorId, localId = x.Key.localId, MaterialId = x.Key.MaterialId }).ToList();

                string sqlMain = string.Empty;

                foreach (var item in checkpackmaterialdata)
                {
                    //获取新制的物料数量
                    var item_N = checkpackmaterial.Where(x => x.MaterialId == item.MaterialId && x.localId == item.localId && x.OldOrNew == 1).FirstOrDefault();
                    double? Nums_N = item_N == null ? 0 : item_N.Nums;
                    //获取翻新的物料数量
                    var item_O = checkpackmaterial.Where(x => x.MaterialId == item.MaterialId && x.localId == item.localId && x.OldOrNew == 0).FirstOrDefault();
                    double? Nums_O = item_O == null ? 0 : item_N.Nums;

                    double? ScanNums = Nums_N + Nums_O;

                    double? Nums_R = 0;
                    //获取当前货位物料的占用数量
                    if (data.PickMaterialOccupy != null)
                    {
                        var item_R = data.PickMaterialOccupy.Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.localId).FirstOrDefault();
                        Nums_R = item_R == null ? 0 : item_R.Nums;
                    }

                    var itemlocadata = Location.Where(x => x.Id == item.localId).FirstOrDefault();

                    IT_LocalMaterial itemmaterial = new IT_LocalMaterial();
                    itemmaterial.Id = IdHelper.GetId();
                    itemmaterial.MaterialId = item.MaterialId;
                    itemmaterial.StorId = item.StorId;
                    itemmaterial.LocalId = item.localId;
                    itemmaterial.Nums_N = Convert.ToDouble(Nums_N);
                    itemmaterial.Nums_O = Convert.ToDouble(Nums_O);
                    itemmaterial.Nums_R = Convert.ToDouble(Nums_R);
                    itemmaterial.CreatorId = _operator.UserId;
                    itemmaterial.CreateTime = DateTime.Now;
                    itemmaterial.Deleted = false;
                    itemmaterial.AreaId = itemlocadata.AreaId;
                    itemmaterial.RackId = itemlocadata.RackId;
                    itemmaterial.ScanNum = Convert.ToDouble(ScanNums);
                    itemmaterial.CheckNum = 0;
                    CheckLocalMaterialList.Add(itemmaterial);
                }

                //修改盘点单状态为已完成
                sqlMain += @" update TD_Check set Status=4,IsComplete=1 where Id='" + data.checkId + "'; ";

                //保存盘点库存明细记录
                if (data.CheckStockDetail != null)
                {
                    Db.Insert<TD_CheckStockDetail>(data.CheckStockDetail);
                }
                //保存盘点库存明细
                Db.Insert<IT_LocalDetail>(LocalDetailList);
                //保存盘点库存汇总
                Db.Insert<IT_LocalMaterial>(CheckLocalMaterialList);
                //保存入库单
                if (InStorDetailList != null)
                {
                    Db.Insert<TD_InStorDetail>(InStorDetailList);
                    Db.Insert<TD_InStorRecord>(InStorRecordList);
                    Db.Insert<TD_InStorage>(InStorageList);
                }
                //保存出库单
                if (OutStorDetailList != null)
                {
                    Db.Insert<TD_OutStorDetail>(OutStorDetailList);
                    Db.Insert<TD_OutStorRecord>(OutStorRecordList);
                    Db.Insert<TD_OutStorage>(OutStorageList);
                }
                //修改盘点单状态
                Db.ExecuteSql(sqlMain);
            }
            catch (Exception ex)
            {
                throw new BusException("请检查数据是否有误或网络是否正常");
            }
        }

        /// <summary>
        /// 获取盘点单实际盘点信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<ChcekPackMaterialDTO>> GetChcekPackMaterialListAsync(PageInput<CheckConditionDTO> input)
        {
            var search = input.Search;
            string sql = @"select ROW_NUMBER() OVER (ORDER BY a.MaterialId ) row_num,a.CheckId,a.MaterialId,b.`Name` as MaterialName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,a.StorId,d.`Name` as StorName,a.localId,c.StorAreaName,SUM(Nums) as Nums from TD_CheckPack as a
left join PB_Material as b on a.MaterialId=b.Id
left join View_StorAreaRackLocation as c on a.localId=c.Id
left join Base_Department as d on a.StorId=d.Id
 where CheckId='{0}'
 group by a.CheckId,a.MaterialId,b.`Name`,b.`Code`,b.Spec,a.StorId,d.`Name`,a.localId,c.StorAreaName";
            string sqlMain = string.Format(sql, search.checkId);

            var lidata = await Db.GetListBySqlAsync<ChcekPackMaterialDTO>(sqlMain);
            int num = lidata.Count;
            var list = lidata
               .Skip((input.PageIndex - 1) * input.PageRows)
               .Take(input.PageRows).ToList();
            return new PageResult<ChcekPackMaterialDTO> { Data = list, Total = num };

        }

    /// <summary>
    /// PDA扫描盘点单扫描货位获取明细物料信息
    /// </summary>
    /// <param name="panId">盘点单id</param>
    /// <param name="locationId">货位id</param>
    /// <param name="MaterName">物料名称</param>
    /// <returns></returns>
        public async Task<List<CheckMateralInfo>> GetCheckMateralInfo(string panId,string locationId,string MaterName)
        {
            //获取盘点信息
            var CheckData =await Db.GetIQueryable<TD_Check>().Where(m=>m.Id==panId).FirstOrDefaultAsync();
            //验证盘点单号是否存在
            if (CheckData != null)
            {
                        Expression<Func<TD_CheckData, PB_Material, CheckMateralInfo>> select = (a, b) => new CheckMateralInfo
                        {
                            MaterailCode=b.Code,
                            MaterailName=b.Name,
                            MatetailSpec=b.Spec,
                            CheckId=a.CheckId,
                            MaterailId=b.Id,
                            LocaNum=a.LocalNum,
                            locationId=a.localId,
                        };
                        select = select.BuildExtendSelectExpre();
                        var k = from a in Db.GetIQueryable<TD_CheckData>().AsExpandable()
                                join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                                from b in ab.DefaultIfEmpty()
                                select @select.Invoke(a, b);
                        k = k.Where(m=>m.CheckId==panId&&m.locationId==locationId);
                        var res =await k.ToListAsync();
                if (!MaterName.IsNullOrEmpty()) {
                    k = k.Where(m=>m.MaterailName.Contains(MaterName)||m.MaterailCode.Contains(MaterName));
                }
                        res.OrderByDescending(m=>m.MaterailId);  
                        return  res;
                
            }
            else {
                throw new BusException("盘点单号不存在");
            }
            
        }

        #endregion

        #region 查询未完成的单据

        /// <summary>
        /// 查询未完成的备货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_PickUpMain>> GetCheckPickUpMainListAsync(PageInput<ConditionDTO> input)
        {
            var where = LinqHelper.True<PB_PickUpMain>();
            var search = input.Search;
            var q = Db.GetIQueryable<PB_PickUpMain>();
            q = q.Where(x => x.Status < 3);
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 查询未完成的收货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<TD_Receiving>> GetCheckReceivingListAsync(PageInput<ConditionDTO> input)
        {
            var where = LinqHelper.True<TD_Receiving>();
            var search = input.Search;
            var q = Db.GetIQueryable<TD_Receiving>();
            q = q.Where(x => x.Status < 4);
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 查询未完成的收货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_TransportBillDTO>> GetCheckTransportBillListAsync(PageInput<ConditionDTO> input)
        {
            List<string> ids = new List<string>();
            List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.TrueOrFalse == false ).ToListAsync();
            var billdata = TransportBillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).ToList();
            foreach (var item in billdata)
            {
                ids.Add(item.ParentId);
            }
            var where = LinqHelper.True<PB_TransportBillDTO>();
            var search = input.Search;
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                    from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            q = q.Where(x => ids.Contains(x.Id));
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 查询盘点单是否可以保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<Object> GetCheckTrueOrFalseAsync(TD_CheckDTO data)
        {
            List<CheckReceivingDTO> Receiving = new List<CheckReceivingDTO>();
            List<CheckPickUpMainDTO> PickUpMain = new List<CheckPickUpMainDTO>();
            List<CheckTranBillDTO> TranBill = new List<CheckTranBillDTO>();
            List<IT_LocalMaterial> listdata = new List<IT_LocalMaterial>();
            List<string> localIds = new List<string>();
            List<string> materialids = new List<string>();
            if (data.Type == "1")
            {
                List<PB_PickUpMain> PickUpMainlist = await Db.GetIQueryable<PB_PickUpMain>().Where(x => x.Status < 3).ToListAsync();
                foreach (var item in PickUpMainlist)
                {
                    CheckPickUpMainDTO itemdata = new CheckPickUpMainDTO();
                    itemdata.Id = item.Id;
                    itemdata.CreateTime = item.CreateTime;
                    itemdata.BuildingId = item.BuildingId;
                    itemdata.OrderType = item.OrderType;
                    itemdata.StyleName = item.StyleName;
                    itemdata.Status = item.Status;
                    PickUpMain.Add(itemdata);
                }
                List<TD_Receiving> Receivinglist = await Db.GetIQueryable<TD_Receiving>().Where(x => x.Status < 4).ToListAsync();
                foreach (var item in Receivinglist)
                {
                    CheckReceivingDTO itemdata = new CheckReceivingDTO();
                    itemdata.Id = item.Id;
                    itemdata.RecTime = item.RecTime;
                    itemdata.TotalNum = item.TotalNum;
                    itemdata.InNum = item.InNum;
                    itemdata.Status = item.Status;
                    Receiving.Add(itemdata);
                }
                //查询未处理的装车异常
                List<string> ids = new List<string>();
                List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.TrueOrFalse == false && x.IsHandle == false).ToListAsync();
                var billdata = TransportBillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).ToList();
                foreach (var item in billdata)
                {
                    ids.Add(item.ParentId);
                }
                Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                        from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var TranBillList = await q.Where(x => ids.Contains(x.Id)).ToListAsync();
                var billlist = TranBillList.GroupBy(x => new { x.Id, x.SendTime, x.PlateNO, x.TransportType }).Select(x => new { Id = x.Key.Id, SendTime = x.Key.SendTime, PlateNO = x.Key.PlateNO, TransportType = x.Key.TransportType }).ToList();
                foreach (var item in billlist)
                {
                    CheckTranBillDTO itemdata = new CheckTranBillDTO();
                    itemdata.Id = item.Id;
                    itemdata.SendTime = item.SendTime;
                    itemdata.PlateNO = item.PlateNO;
                    itemdata.TransportType = item.TransportType;
                    TranBill.Add(itemdata);
                }
            }
            else if (data.Type == "2")
            {
                //获取要盘点的仓库下物料信息
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.StorId == data.StorId).ToListAsync();
                //获取仓库下的货位信息
                List<PB_Location> LocationList = await Db.GetIQueryable<PB_Location>().Where(x => x.StorId == data.StorId).ToListAsync();
                foreach (var item in LocationList)
                {
                    localIds.Add(item.Id);
                }
                //查询备货单
                Expression<Func<PB_PickUpMain, PB_PickUpList, CheckPickUpMainDTO>> pickselect = (a, b) => new CheckPickUpMainDTO
                {
                    MaterialId = b.MaterialId,
                    LocalId = b.LocationId
                };
                pickselect = pickselect.BuildExtendSelectExpre();
                var pick = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                        join b in Db.GetIQueryable<PB_PickUpList>() on a.Id equals b.ParentId into ab
                        from b in ab.DefaultIfEmpty()
                        select @pickselect.Invoke(a, b);
                var CheckPickList = await pick.Where(x => x.Status < 3 && localIds.Contains(x.LocalId)).ToListAsync();
                var picklist = CheckPickList.GroupBy(x => new { x.Id, x.CreateTime, x.BuildingId, x.OrderType, x.StyleName, x.Status }).Select(x => new { Id = x.Key.Id, CreateTime = x.Key.CreateTime, BuildingId = x.Key.BuildingId, OrderType = x.Key.OrderType, StyleName = x.Key.StyleName, Status = x.Key.Status }).ToList();
                foreach (var item in picklist)
                {
                    CheckPickUpMainDTO itemdata = new CheckPickUpMainDTO();
                    itemdata.Id = item.Id;
                    itemdata.CreateTime = item.CreateTime;
                    itemdata.BuildingId = item.BuildingId;
                    itemdata.OrderType = item.OrderType;
                    itemdata.StyleName = item.StyleName;
                    itemdata.Status = item.Status;
                    PickUpMain.Add(itemdata);
                }
                //查询收货单
                var materialdata = listdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                foreach (var item in materialdata)
                {
                    materialids.Add(item.MaterialId);
                }
                Expression<Func<TD_Receiving, TD_RecDetail, CheckReceivingDTO>> receselect = (a, b) => new CheckReceivingDTO
                {
                    MaterialId = b.MaterialId
                };
                receselect = receselect.BuildExtendSelectExpre();
                var rece = from a in Db.GetIQueryable<TD_Receiving>().AsExpandable()
                           join b in Db.GetIQueryable<TD_RecDetail>() on a.Id equals b.RecId into ab
                           from b in ab.DefaultIfEmpty()
                           select @receselect.Invoke(a, b);
                var ReceivingList = await rece.Where(x => x.Status < 4 && materialids.Contains(x.MaterialId)).ToListAsync();
                var Recelist = ReceivingList.GroupBy(x => new { x.Id, x.RecTime, x.TotalNum, x.InNum, x.Status }).Select(x => new { Id = x.Key.Id, RecTime = x.Key.RecTime, TotalNum = x.Key.TotalNum, InNum = x.Key.InNum, Status = x.Key.Status }).ToList();
                foreach (var item in Recelist)
                {
                    CheckReceivingDTO itemdata = new CheckReceivingDTO();
                    itemdata.Id = item.Id;
                    itemdata.RecTime = item.RecTime;
                    itemdata.TotalNum = item.TotalNum;
                    itemdata.InNum = item.InNum;
                    itemdata.Status = item.Status;
                    Receiving.Add(itemdata);
                }

                //查询未处理的装车异常
                List<string> ids = new List<string>();
                List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.TrueOrFalse == false && x.IsHandle == false && materialids.Contains(x.MaterialId)).ToListAsync();
                var billdata = TransportBillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).ToList();
                foreach (var item in billdata)
                {
                    ids.Add(item.ParentId);
                }
                Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                        from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var TranBillList = await q.Where(x => ids.Contains(x.Id)).ToListAsync();
                var billlist = TranBillList.GroupBy(x => new { x.Id, x.SendTime, x.PlateNO, x.TransportType }).Select(x => new { Id = x.Key.Id, SendTime = x.Key.SendTime, PlateNO = x.Key.PlateNO, TransportType = x.Key.TransportType }).ToList();
                foreach (var item in billlist)
                {
                    CheckTranBillDTO itemdata = new CheckTranBillDTO();
                    itemdata.Id = item.Id;
                    itemdata.SendTime = item.SendTime;
                    itemdata.PlateNO = item.PlateNO;
                    itemdata.TransportType = item.TransportType;
                    TranBill.Add(itemdata);
                }
            }
            else if (data.Type == "3")
            {
                //获取要盘点的仓库下物料信息
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.StorId == data.StorId && data.ListIds.Contains(x.MaterialId)).ToListAsync();
                foreach (var item in listdata)
                {
                    localIds.Add(item.LocalId);
                }
                //查询备货单
                Expression<Func<PB_PickUpMain, PB_PickUpList, CheckPickUpMainDTO>> pickselect = (a, b) => new CheckPickUpMainDTO
                {
                    MaterialId = b.MaterialId,
                    LocalId = b.LocationId
                };
                pickselect = pickselect.BuildExtendSelectExpre();
                var pick = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                           join b in Db.GetIQueryable<PB_PickUpList>() on a.Id equals b.ParentId into ab
                           from b in ab.DefaultIfEmpty()
                           select @pickselect.Invoke(a, b);
                var CheckPickList = await pick.Where(x => x.Status < 3 && localIds.Contains(x.LocalId) && data.ListIds.Contains(x.MaterialId)).ToListAsync();
                var picklist = CheckPickList.GroupBy(x => new { x.Id, x.CreateTime, x.BuildingId, x.OrderType, x.StyleName, x.Status }).Select(x => new { Id = x.Key.Id, CreateTime = x.Key.CreateTime, BuildingId = x.Key.BuildingId, OrderType = x.Key.OrderType, StyleName = x.Key.StyleName, Status = x.Key.Status }).ToList();
                foreach (var item in picklist)
                {
                    CheckPickUpMainDTO itemdata = new CheckPickUpMainDTO();
                    itemdata.Id = item.Id;
                    itemdata.CreateTime = item.CreateTime;
                    itemdata.BuildingId = item.BuildingId;
                    itemdata.OrderType = item.OrderType;
                    itemdata.StyleName = item.StyleName;
                    itemdata.Status = item.Status;
                    PickUpMain.Add(itemdata);
                }
                //查询收货单
                var materialdata = listdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                Expression<Func<TD_Receiving, TD_RecDetail, CheckReceivingDTO>> receselect = (a, b) => new CheckReceivingDTO
                {
                    MaterialId = b.MaterialId
                };
                receselect = receselect.BuildExtendSelectExpre();
                var rece = from a in Db.GetIQueryable<TD_Receiving>().AsExpandable()
                           join b in Db.GetIQueryable<TD_RecDetail>() on a.Id equals b.RecId into ab
                           from b in ab.DefaultIfEmpty()
                           select @receselect.Invoke(a, b);
                var ReceivingList = await rece.Where(x => x.Status < 4 && data.ListIds.Contains(x.MaterialId)).ToListAsync();
                var Recelist = ReceivingList.GroupBy(x => new { x.Id, x.RecTime, x.TotalNum, x.InNum, x.Status }).Select(x => new { Id = x.Key.Id, RecTime = x.Key.RecTime, TotalNum = x.Key.TotalNum, InNum = x.Key.InNum, Status = x.Key.Status }).ToList();
                foreach (var item in Recelist)
                {
                    CheckReceivingDTO itemdata = new CheckReceivingDTO();
                    itemdata.Id = item.Id;
                    itemdata.RecTime = item.RecTime;
                    itemdata.TotalNum = item.TotalNum;
                    itemdata.InNum = item.InNum;
                    itemdata.Status = item.Status;
                    Receiving.Add(itemdata);
                }
                //查询未处理的装车异常
                List<string> ids = new List<string>();
                List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.TrueOrFalse == false && x.IsHandle == false && materialids.Contains(x.MaterialId)).ToListAsync();
                var billdata = TransportBillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).ToList();
                foreach (var item in billdata)
                {
                    ids.Add(item.ParentId);
                }
                Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                        from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var TranBillList = await q.Where(x => ids.Contains(x.Id)).ToListAsync();
                var billlist = TranBillList.GroupBy(x => new { x.Id, x.SendTime, x.PlateNO, x.TransportType }).Select(x => new { Id = x.Key.Id, SendTime = x.Key.SendTime, PlateNO = x.Key.PlateNO, TransportType = x.Key.TransportType }).ToList();
                foreach (var item in billlist)
                {
                    CheckTranBillDTO itemdata = new CheckTranBillDTO();
                    itemdata.Id = item.Id;
                    itemdata.SendTime = item.SendTime;
                    itemdata.PlateNO = item.PlateNO;
                    itemdata.TransportType = item.TransportType;
                    TranBill.Add(itemdata);
                }
            }
            else if (data.Type == "4")
            {
                //获取仓库下的货位信息
                List<PB_Location> LocationList = await Db.GetIQueryable<PB_Location>().Where(x => x.AreaId == data.StorAreaId).ToListAsync();
                foreach (var item in LocationList)
                {
                    localIds.Add(item.Id);
                }
                //查询备货单
                Expression<Func<PB_PickUpMain, PB_PickUpList, CheckPickUpMainDTO>> pickselect = (a, b) => new CheckPickUpMainDTO
                {
                    MaterialId = b.MaterialId,
                    LocalId = b.LocationId
                };
                pickselect = pickselect.BuildExtendSelectExpre();
                var pick = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                           join b in Db.GetIQueryable<PB_PickUpList>() on a.Id equals b.ParentId into ab
                           from b in ab.DefaultIfEmpty()
                           select @pickselect.Invoke(a, b);
                var CheckPickList = await pick.Where(x => x.Status < 3 && localIds.Contains(x.LocalId)).ToListAsync();
                var picklist = CheckPickList.GroupBy(x => new { x.Id, x.CreateTime, x.BuildingId, x.OrderType, x.StyleName, x.Status }).Select(x => new { Id = x.Key.Id, CreateTime = x.Key.CreateTime, BuildingId = x.Key.BuildingId, OrderType = x.Key.OrderType, StyleName = x.Key.StyleName, Status = x.Key.Status }).ToList();
                foreach (var item in picklist)
                {
                    CheckPickUpMainDTO itemdata = new CheckPickUpMainDTO();
                    itemdata.Id = item.Id;
                    itemdata.CreateTime = item.CreateTime;
                    itemdata.BuildingId = item.BuildingId;
                    itemdata.OrderType = item.OrderType;
                    itemdata.StyleName = item.StyleName;
                    itemdata.Status = item.Status;
                    PickUpMain.Add(itemdata);
                }
                //获取要盘点的仓库下物料信息
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => localIds.Contains(x.LocalId)).ToListAsync();
                //查询收货单
                var materialdata = listdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                foreach (var item in materialdata)
                {
                    materialids.Add(item.MaterialId);
                }
                Expression<Func<TD_Receiving, TD_RecDetail, CheckReceivingDTO>> receselect = (a, b) => new CheckReceivingDTO
                {
                    MaterialId = b.MaterialId
                };
                receselect = receselect.BuildExtendSelectExpre();
                var rece = from a in Db.GetIQueryable<TD_Receiving>().AsExpandable()
                           join b in Db.GetIQueryable<TD_RecDetail>() on a.Id equals b.RecId into ab
                           from b in ab.DefaultIfEmpty()
                           select @receselect.Invoke(a, b);
                var ReceivingList = await rece.Where(x => x.Status < 4 && materialids.Contains(x.MaterialId)).ToListAsync();
                var Recelist = ReceivingList.GroupBy(x => new { x.Id, x.RecTime, x.TotalNum, x.InNum, x.Status }).Select(x => new { Id = x.Key.Id, RecTime = x.Key.RecTime, TotalNum = x.Key.TotalNum, InNum = x.Key.InNum, Status = x.Key.Status }).ToList();
                foreach (var item in Recelist)
                {
                    CheckReceivingDTO itemdata = new CheckReceivingDTO();
                    itemdata.Id = item.Id;
                    itemdata.RecTime = item.RecTime;
                    itemdata.TotalNum = item.TotalNum;
                    itemdata.InNum = item.InNum;
                    itemdata.Status = item.Status;
                    Receiving.Add(itemdata);
                }
                //查询未处理的装车异常
                List<string> ids = new List<string>();
                List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.TrueOrFalse == false && x.IsHandle == false && materialids.Contains(x.MaterialId)).ToListAsync();
                var billdata = TransportBillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).ToList();
                foreach (var item in billdata)
                {
                    ids.Add(item.ParentId);
                }
                Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                        from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var TranBillList = await q.Where(x => ids.Contains(x.Id)).ToListAsync();
                var billlist = TranBillList.GroupBy(x => new { x.Id, x.SendTime, x.PlateNO, x.TransportType }).Select(x => new { Id = x.Key.Id, SendTime = x.Key.SendTime, PlateNO = x.Key.PlateNO, TransportType = x.Key.TransportType }).ToList();
                foreach (var item in billlist)
                {
                    CheckTranBillDTO itemdata = new CheckTranBillDTO();
                    itemdata.Id = item.Id;
                    itemdata.SendTime = item.SendTime;
                    itemdata.PlateNO = item.PlateNO;
                    itemdata.TransportType = item.TransportType;
                    TranBill.Add(itemdata);
                }
            }
            else if (data.Type == "5")
            {
                //获取仓库下的货位信息
                List<PB_Location> LocationList = await Db.GetIQueryable<PB_Location>().Where(x => x.RackId == data.StorRackId).ToListAsync();
                foreach (var item in LocationList)
                {
                    localIds.Add(item.Id);
                }
                //查询备货单
                Expression<Func<PB_PickUpMain, PB_PickUpList, CheckPickUpMainDTO>> pickselect = (a, b) => new CheckPickUpMainDTO
                {
                    MaterialId = b.MaterialId,
                    LocalId = b.LocationId
                };
                pickselect = pickselect.BuildExtendSelectExpre();
                var pick = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                           join b in Db.GetIQueryable<PB_PickUpList>() on a.Id equals b.ParentId into ab
                           from b in ab.DefaultIfEmpty()
                           select @pickselect.Invoke(a, b);
                var CheckPickList = await pick.Where(x => x.Status < 3 && localIds.Contains(x.LocalId)).ToListAsync();
                var picklist = CheckPickList.GroupBy(x => new { x.Id, x.CreateTime, x.BuildingId, x.OrderType, x.StyleName, x.Status }).Select(x => new { Id = x.Key.Id, CreateTime = x.Key.CreateTime, BuildingId = x.Key.BuildingId, OrderType = x.Key.OrderType, StyleName = x.Key.StyleName, Status = x.Key.Status }).ToList();
                foreach (var item in picklist)
                {
                    CheckPickUpMainDTO itemdata = new CheckPickUpMainDTO();
                    itemdata.Id = item.Id;
                    itemdata.CreateTime = item.CreateTime;
                    itemdata.BuildingId = item.BuildingId;
                    itemdata.OrderType = item.OrderType;
                    itemdata.StyleName = item.StyleName;
                    itemdata.Status = item.Status;
                    PickUpMain.Add(itemdata);
                }
                //获取要盘点的仓库下物料信息
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => localIds.Contains(x.LocalId)).ToListAsync();
                //查询收货单
                var materialdata = listdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                foreach (var item in materialdata)
                {
                    materialids.Add(item.MaterialId);
                }
                Expression<Func<TD_Receiving, TD_RecDetail, CheckReceivingDTO>> receselect = (a, b) => new CheckReceivingDTO
                {
                    MaterialId = b.MaterialId
                };
                receselect = receselect.BuildExtendSelectExpre();
                var rece = from a in Db.GetIQueryable<TD_Receiving>().AsExpandable()
                           join b in Db.GetIQueryable<TD_RecDetail>() on a.Id equals b.RecId into ab
                           from b in ab.DefaultIfEmpty()
                           select @receselect.Invoke(a, b);
                var ReceivingList = await rece.Where(x => x.Status < 4 && materialids.Contains(x.MaterialId)).ToListAsync();
                var Recelist = ReceivingList.GroupBy(x => new { x.Id, x.RecTime, x.TotalNum, x.InNum, x.Status }).Select(x => new { Id = x.Key.Id, RecTime = x.Key.RecTime, TotalNum = x.Key.TotalNum, InNum = x.Key.InNum, Status = x.Key.Status }).ToList();
                foreach (var item in Recelist)
                {
                    CheckReceivingDTO itemdata = new CheckReceivingDTO();
                    itemdata.Id = item.Id;
                    itemdata.RecTime = item.RecTime;
                    itemdata.TotalNum = item.TotalNum;
                    itemdata.InNum = item.InNum;
                    itemdata.Status = item.Status;
                    Receiving.Add(itemdata);
                }
                //查询未处理的装车异常
                List<string> ids = new List<string>();
                List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.TrueOrFalse == false && x.IsHandle == false && materialids.Contains(x.MaterialId)).ToListAsync();
                var billdata = TransportBillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).ToList();
                foreach (var item in billdata)
                {
                    ids.Add(item.ParentId);
                }
                Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                        from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var TranBillList = await q.Where(x => ids.Contains(x.Id)).ToListAsync();
                var billlist = TranBillList.GroupBy(x => new { x.Id, x.SendTime, x.PlateNO, x.TransportType }).Select(x => new { Id = x.Key.Id, SendTime = x.Key.SendTime, PlateNO = x.Key.PlateNO, TransportType = x.Key.TransportType }).ToList();
                foreach (var item in billlist)
                {
                    CheckTranBillDTO itemdata = new CheckTranBillDTO();
                    itemdata.Id = item.Id;
                    itemdata.SendTime = item.SendTime;
                    itemdata.PlateNO = item.PlateNO;
                    itemdata.TransportType = item.TransportType;
                    TranBill.Add(itemdata);
                }
            }
            else if (data.Type == "6")
            {
                //获取要盘点的仓库下物料信息
                listdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.LocalId == data.StorLocaId).ToListAsync();
                //查询备货单
                Expression<Func<PB_PickUpMain, PB_PickUpList, CheckPickUpMainDTO>> pickselect = (a, b) => new CheckPickUpMainDTO
                {
                    MaterialId = b.MaterialId,
                    LocalId = b.LocationId
                };
                pickselect = pickselect.BuildExtendSelectExpre();
                var pick = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                           join b in Db.GetIQueryable<PB_PickUpList>() on a.Id equals b.ParentId into ab
                           from b in ab.DefaultIfEmpty()
                           select @pickselect.Invoke(a, b);
                var CheckPickList = await pick.Where(x => x.Status < 3 && x.LocalId == data.StorLocaId).ToListAsync();
                var picklist = CheckPickList.GroupBy(x => new { x.Id, x.CreateTime, x.BuildingId, x.OrderType, x.StyleName, x.Status }).Select(x => new { Id = x.Key.Id, CreateTime = x.Key.CreateTime, BuildingId = x.Key.BuildingId, OrderType = x.Key.OrderType, StyleName = x.Key.StyleName, Status = x.Key.Status }).ToList();
                foreach (var item in picklist)
                {
                    CheckPickUpMainDTO itemdata = new CheckPickUpMainDTO();
                    itemdata.Id = item.Id;
                    itemdata.CreateTime = item.CreateTime;
                    itemdata.BuildingId = item.BuildingId;
                    itemdata.OrderType = item.OrderType;
                    itemdata.StyleName = item.StyleName;
                    itemdata.Status = item.Status;
                    PickUpMain.Add(itemdata);
                }
                //查询收货单
                var materialdata = listdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).ToList();
                foreach (var item in materialdata)
                {
                    materialids.Add(item.MaterialId);
                }
                Expression<Func<TD_Receiving, TD_RecDetail, CheckReceivingDTO>> receselect = (a, b) => new CheckReceivingDTO
                {
                    MaterialId = b.MaterialId
                };
                receselect = receselect.BuildExtendSelectExpre();
                var rece = from a in Db.GetIQueryable<TD_Receiving>().AsExpandable()
                           join b in Db.GetIQueryable<TD_RecDetail>() on a.Id equals b.RecId into ab
                           from b in ab.DefaultIfEmpty()
                           select @receselect.Invoke(a, b);
                var ReceivingList = await rece.Where(x => x.Status < 4 && materialids.Contains(x.MaterialId)).ToListAsync();
                var Recelist = ReceivingList.GroupBy(x => new { x.Id, x.RecTime, x.TotalNum, x.InNum, x.Status }).Select(x => new { Id = x.Key.Id, RecTime = x.Key.RecTime, TotalNum = x.Key.TotalNum, InNum = x.Key.InNum, Status = x.Key.Status }).ToList();
                foreach (var item in Recelist)
                {
                    CheckReceivingDTO itemdata = new CheckReceivingDTO();
                    itemdata.Id = item.Id;
                    itemdata.RecTime = item.RecTime;
                    itemdata.TotalNum = item.TotalNum;
                    itemdata.InNum = item.InNum;
                    itemdata.Status = item.Status;
                    Receiving.Add(itemdata);
                }
                //查询未处理的装车异常
                List<string> ids = new List<string>();
                List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.TrueOrFalse == false && x.IsHandle == false && materialids.Contains(x.MaterialId)).ToListAsync();
                var billdata = TransportBillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).ToList();
                foreach (var item in billdata)
                {
                    ids.Add(item.ParentId);
                }
                Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                        from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d);
                var TranBillList = await q.Where(x => ids.Contains(x.Id)).ToListAsync();
                var billlist = TranBillList.GroupBy(x => new { x.Id, x.SendTime, x.PlateNO, x.TransportType }).Select(x => new { Id = x.Key.Id, SendTime = x.Key.SendTime, PlateNO = x.Key.PlateNO, TransportType = x.Key.TransportType }).ToList();
                foreach (var item in billlist)
                {
                    CheckTranBillDTO itemdata = new CheckTranBillDTO();
                    itemdata.Id = item.Id;
                    itemdata.SendTime = item.SendTime;
                    itemdata.PlateNO = item.PlateNO;
                    itemdata.TransportType = item.TransportType;
                    TranBill.Add(itemdata);
                }
            }
            CheckBillData cbdata = new CheckBillData();
            if (Receiving.Count > 0 || PickUpMain.Count > 0)
            {
                cbdata.ErrorCode = 1;
                cbdata.Success = false;
                cbdata.Receiving = Receiving;
                cbdata.PickUpMain = PickUpMain;
                cbdata.TranBill = TranBill;
            }
            else
            {
                cbdata.ErrorCode = 0;
                cbdata.Success = true;

            }
            return cbdata;
        }

        #endregion

        #region 私有成员

        #endregion
    }
}